package com.manli.api.service.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.manli.api.base.exception.MyException;
import com.manli.api.dao.*;
import com.manli.api.dao.wechat.WeChatUserInfoDao;
import com.manli.api.dto.*;
import com.manli.api.enums.ResultEnums;
import com.manli.api.pojo.*;
import com.manli.api.service.SearchLogService;
import com.manli.api.util.*;
import com.manli.common.utils.RandomUtils;
import com.manli.wechat.pojo.WeChatUserInfo;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class WechatShopService {
    @Autowired
    private SQLManager sqlManager;
    @Autowired
    private VisitLogDao visitLogDao;
    @Autowired
    private SearchLogService searchLogService;
    @Autowired
    private SearchLogDao searchLogDao;
    @Autowired
    private SessionInfoUtils sessionInfoUtils;
    @Autowired
    private NoticeTipLogDao noticeTipLogDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ActivityLogDao activityLogDao;
    @Autowired
    private WeChatUserInfoDetailDao weChatUserInfoDetailDao;
    @Autowired
    private AliYunSmsUtil aliYunSmsUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ManliSpaceDao manliSpaceDao;
    @Autowired
    private ManliSpaceLogDao manliSpaceLogDao;
    @Autowired
    private ManliSpaceLikeCountLogDao manliSpaceLikeCountLogDao;
    @Autowired
    private WeChatPushMessageUtil weChatPushMessageUtil;
    @Autowired
    private ViewStockInfoDao viewStockInfoDao;
    @Autowired
    private ViewOrderGoodsDao viewOrderGoodsDao;
    @Autowired
    private AppraiseLogDao appraiseLogDao;
    @Autowired
    private WeChatUserInfoDao weChatUserInfoDao;


    public Result letBuy(QueryParamsLetBuy queryParamsLetBuy) {
        ObjectEmptyUtil.letBuyIsEmpty(queryParamsLetBuy);
        //先查询正在种草活动时间范围内的已经上架的活动商品列表。 关联查询店家
        String sql = "select * from (select * from ( " +
                "SELECT " +
                " b.*, " +
                " d.goods_model_name, " +
                " min(d.goods_model_sale_price) goods_model_sale_price, " +
                " c.longitude, " +
                " c.latitude  " +
                "FROM " +
                " recommend_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id  " +
                " LEFT JOIN partner c ON b.partner_id = c.partner_id " +
                " LEFT JOIN goods_model d ON b.goods_def_id = d.goods_def_id  " +
                "WHERE " +
                " a.activity_type_id = 4  " +
                " AND a.status = '1'  " +
                " AND b.partner_id IS NOT NULL  " +
                " AND a.activity_start_time < now() AND a.activity_end_time > now()  " +
                " AND b.status = 1 " +
                ("1".equals(queryParamsLetBuy.getBuyMethod())?" and b.buy_method = '1'":" and b.buy_method != '1'") +
                " UNION ALL " +
                "SELECT " +
                " b.*, " +
                " d.goods_model_name, " +
                " min(d.goods_model_sale_price) goods_model_sale_price, " +
                " c.longitude, " +
                " c.latitude  " +
                "FROM " +
                " recommend_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id  " +
                " LEFT JOIN branch c ON b.branch_id = c.branch_id " +
                " LEFT JOIN goods_model d ON b.goods_def_id = d.goods_def_id  " +
                "WHERE " +
                " a.activity_type_id = 4  " +
                " AND a.status = '1'  " +
                " AND b.partner_id IS NULL  " +
                " AND a.activity_start_time < now() AND a.activity_end_time > now()  " +
                " AND b.status = 1 " +
                ("1".equals(queryParamsLetBuy.getBuyMethod())?" and b.buy_method = '1'":" and b.buy_method != '1'") +
                ") t HAVING t.goods_def_id is not null ) main";
        SQLReady sqlReady = new SQLReady(sql);
        PageQuery<Map> pageQuery = new PageQuery<Map>(queryParamsLetBuy.getPage().longValue(),queryParamsLetBuy.getLimit().longValue());
        PageQuery<Map> executePageQuery = sqlManager.execute(sqlReady, Map.class,pageQuery);
        List<Map> list = executePageQuery.getList();
        if(list.size() > 0 ){
            if(StringUtils.isEmpty(queryParamsLetBuy.getLongitude())){
                //没传经纬度，不进行距离排序
                return ResultUtil.success(list,pageQuery.getTotalRow());
            }else{
                //传了经纬度，进行距离排序
                LocationPoint p1 = new LocationPoint(Double.parseDouble(queryParamsLetBuy.getLongitude()),Double.parseDouble(queryParamsLetBuy.getLatitude()));
                list.stream().forEach(map -> {
                    LocationPoint p2 = new LocationPoint(Double.parseDouble(map.get("longitude").toString()) ,Double.parseDouble(map.get("latitude").toString()));
                    map.put("distance",LocationUtils.getDistance(p1,p2));
                });
                List<Map> sortedList = list.stream().sorted(Comparator.comparing(map -> {
                    return (Double)map.get("distance");
                })).collect(Collectors.toList());

                return ResultUtil.success(sortedList,pageQuery.getTotalRow());
            }
        }
        return ResultUtil.success();
    }

    public Result goodsList(QueryParamsGoodsList queryParamsLetBuy) {
        ObjectEmptyUtil.goodsListIsEmpty(queryParamsLetBuy);
        //先查询正在种草活动时间范围内的已经上架的活动商品列表。 关联查询店家
        String sql = "select * from ( " +
                "SELECT " +
                " b.*, " +
                " d.goods_model_name, " +
                " d.goods_model_sale_price, " +
                " e.label1, " +
                " e.label2, " +
                " e.label3, " +
                " e.month_trade_count, " +
                " IFNULL(e.score,'8.00') score, " +
                " c.longitude, " +
                " c.latitude  " +
                "FROM " +
                " goods_def b  " +
                " LEFT JOIN partner c ON b.partner_id = c.partner_id  " +
                " left join (select * from goods_model group by goods_def_id) d on b.goods_def_id = d.goods_def_id  " +
                " left join goods_evainfo e on b.goods_def_id = e.goods_def_id " +
                "WHERE " +
                " b.partner_id is not null  " +
                " AND b.STATUS = 1 and d.status = 1 and b.goods_def_id not in (select goods_def_id from activity_goods) " +
                ("1".equals(queryParamsLetBuy.getBuyMethod())?" and b.buy_method = '1'":" and b.buy_method != '1'") +
                " union all  " +
                " SELECT " +
                " b.*, " +
                " d.goods_model_name, " +
                " d.goods_model_sale_price, " +
                " e.label1, " +
                " e.label2, " +
                " e.label3, " +
                " e.month_trade_count, " +
                " IFNULL(e.score,'8.00') score, " +
                " c.longitude, " +
                " c.latitude  " +
                "FROM " +
                " goods_def b  " +
                " LEFT JOIN branch c ON b.branch_id = c.branch_id  " +
                " left join (select * from goods_model group by goods_def_id) d on b.goods_def_id = d.goods_def_id  " +
                " left join goods_evainfo e on b.goods_def_id = e.goods_def_id " +
                "WHERE " +
                " b.partner_id is null  " +
                " AND b.STATUS = 1 and d.status = 1 and b.goods_def_id not in (select goods_def_id from activity_goods)  " +
                ("1".equals(queryParamsLetBuy.getBuyMethod())?" and b.buy_method = '1'":" and b.buy_method != '1'") +
                ") t ";
        SQLReady sqlReady = new SQLReady(sql);
        PageQuery<Map> pageQuery = new PageQuery<Map>(queryParamsLetBuy.getPage().longValue(),queryParamsLetBuy.getLimit().longValue());
        PageQuery<Map> executePageQuery = sqlManager.execute(sqlReady, Map.class,pageQuery);
        List<Map> list = executePageQuery.getList();
        if(list.size() > 0 ){
            if(StringUtils.isEmpty(queryParamsLetBuy.getLongitude())){
                //没传经纬度，不进行距离排序
                return ResultUtil.success(list,pageQuery.getTotalRow());
            }else{
                //传了经纬度，进行距离排序
                LocationPoint p1 = new LocationPoint(Double.parseDouble(queryParamsLetBuy.getLongitude()),Double.parseDouble(queryParamsLetBuy.getLatitude()));
                list.stream().forEach(map -> {
                    if(map.get("longitude") == null || map.get("latitude") == null){
                        map.put("distance",9999999.9);
                    }else{
                        LocationPoint p2 = new LocationPoint(Double.parseDouble(map.get("longitude").toString()) ,Double.parseDouble(map.get("latitude").toString()));
                        map.put("distance",LocationUtils.getDistance(p1,p2));
                    }
                });
                List<Map> sortedList = list.stream().sorted(Comparator.comparing(map -> {
                    return (Double)map.get("distance");
                })).collect(Collectors.toList());

                return ResultUtil.success(sortedList,pageQuery.getTotalRow());
            }
        }
        return ResultUtil.success();
    }

    public Result goodsBrowsingHistory(QueryParamsGoodsBrowsing queryParamsGoodsBrowsing,HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        ObjectEmptyUtil.goodsBrowsingIsEmpty(queryParamsGoodsBrowsing);
        String sql ="select * from (SELECT DISTINCT " +
                "        a.visit_log_id, " +
                "        'v' as logType, " +
                "        a.openid, " +
                "                a.unionid, " +
                "                a.goods_def_id, " +
                "                max(a.create_time) AS create_time, " +
                "                b.nickname " +
                "        FROM " +
                "        visit_log a " +
                "        LEFT JOIN we_chat_user_info b ON a.unionid = b.unionid " +
                "        WHERE " +
                "        datediff(NOW(), a.create_time) <= 14 " +
                "        AND a.goods_def_id = ? " +
                "        GROUP BY " +
                "        a.unionid " +
                "union " +
                "select " +
                "oi.order_info_id,  " +
                "'b' as logType," +
                "oi.buyer_openid,  " +
                "oi.buyer_unionid,  " +
                "oi.goods_def_id,  " +
                "max(oi.create_time) AS create_time,  " +
                "bb.nickname  " +
                " from order_info oi " +
                "LEFT JOIN we_chat_user_info bb ON oi.buyer_unionid = bb.unionid " +
                "WHERE  " +
                "datediff(NOW(), oi.create_time) <= 14  " +
                "AND oi.goods_def_id = ? " +
                "GROUP BY  " +
                "oi.buyer_unionid ) t " +
                "where t.unionid != ? order by t.create_time desc "
                ;
        SQLReady sqlReady = new SQLReady(sql,queryParamsGoodsBrowsing.getGoodsDefId(),queryParamsGoodsBrowsing.getGoodsDefId(),sessionInfo.getWeChatUserInfo().getUnionid());
        PageQuery<VisitLog> pageQuery = new PageQuery<VisitLog>(queryParamsGoodsBrowsing.getPage().longValue(),queryParamsGoodsBrowsing.getLimit().longValue());
        PageQuery<VisitLog> executePageQuery = sqlManager.execute(sqlReady, VisitLog.class,pageQuery);
        List<VisitLog> logs = executePageQuery.getList();
        logs.forEach(visitLog -> {
            try {
                visitLog.setBorwsingTime(DateUtils.calculateTime(visitLog.getCreateTime()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return ResultUtil.success(logs,executePageQuery.getTotalRow());
    }

    @Transactional
    public Result goodsBrowsingHistoryAdd(QueryParamsGoodsBrowsingAdd queryParamsGoodsBrowsingAdd, HttpServletRequest request) {
        if(sessionInfoUtils.getSessionInfoByAuth(request) == null || sessionInfoUtils.getSessionInfoByAuth(request).getWeChatUserInfo()== null){
            return ResultUtil.error(-1,"需要先登录");
        }
        VisitLog visitLog = new VisitLog();
        visitLog.setCreateTime(new Date());
        visitLog.setGoodsDefId(queryParamsGoodsBrowsingAdd.getGoodsDefId());
        visitLog.setOpenid(sessionInfoUtils.getSessionInfoByAuth(request).getWeChatUserInfo().getOpenid());
        visitLog.setUnionid(sessionInfoUtils.getSessionInfoByAuth(request).getWeChatUserInfo().getUnionid());
        visitLogDao.insert(visitLog);
        return ResultUtil.success();
    }

    public Result goodsAppraiseList(QueryParamsGoodsAppraise queryParamsGoodsAppraise) {
        StringBuffer sql = new StringBuffer("select * from (SELECT " +
                " b.we_chat_user_info_id, " +
                " a.*, " +
                " b.nickname, " +
                " b.headimgurl  " +
                "FROM " +
                " appraise_log a " +
                " LEFT JOIN ( SELECT we_chat_user_info_id, unionid, nickname, headimgurl FROM we_chat_user_info GROUP BY unionid ) b ON a.unionid = b.unionid  " +
                "WHERE " +
                " 1 = 1  " +
                " AND a.goods_def_id = ?  " +
                "ORDER BY " +
                " a.create_time DESC) main");

        SQLReady sqlReady = new SQLReady(sql.toString(),queryParamsGoodsAppraise.getGoodsDefId());

        PageQuery<AppraiseLog> pageQuery = new PageQuery<AppraiseLog>(queryParamsGoodsAppraise.getPage().longValue(),queryParamsGoodsAppraise.getLimit().longValue());
        PageQuery<AppraiseLog> query =sqlManager.execute(sqlReady,AppraiseLog.class,pageQuery);
        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    public Result goodsInfo(QueryParamsGoodsBrowsingAdd queryParamsGoodsBrowsingAdd) {
        StringBuffer sql = new StringBuffer(" SELECT " +
                "  b.*, " +
                "  d.goods_model_name, " +
                "  d.goods_model_sale_price, " +
                "  e.label1, " +
                "  e.label2, " +
                "  e.label3, " +
                "  e.month_trade_count, " +
                "  e.score, " +
                "  c.longitude, " +
                "  c.latitude  " +
                " FROM " +
                "  goods_def b " +
                "  LEFT JOIN partner c ON b.partner_id = c.partner_id " +
                "  LEFT JOIN goods_model d ON b.goods_def_id = d.goods_def_id " +
                "  LEFT JOIN goods_evainfo e ON b.goods_def_id = e.goods_def_id  " +
                " WHERE " +
                "  b.branch_id IS NOT NULL  " +
                "  AND b.STATUS = 1  " +
                "  AND d.STATUS = 1  " +
                "  and b.goods_def_id = ? " +
                " order by d.goods_model_sale_price ");

        SQLReady sqlReady = new SQLReady(sql.toString(),queryParamsGoodsBrowsingAdd.getGoodsDefId());

        List<Map> query =sqlManager.execute(sqlReady,Map.class);
        return ResultUtil.success(query.get(0) == null ? null:query.get(0));
    }

    public Result shopInfo(QueryParamsShopInfo queryParamsShopInfo) {
        if(queryParamsShopInfo.getBranchId() == null && queryParamsShopInfo.getPartnerId() == null){
            return ResultUtil.error(-1,"店面id缺失");
        }

        String sql = "";
        SQLReady sqlReady = null;
        if(queryParamsShopInfo.getPartnerId() != null){
            sql = "SELECT " +
                    " a.branch_id," +
                    " a.partner_id," +
                    " a.partner_name shop_name, " +
                    " a.partner_head_img shop_img, " +
                    " ifnull(ROUND( AVG( b.appraise_score ), 1 ),8) score, " +
                    " ifnull(ROUND( AVG( b.appraise_taste_score ), 1 ),8) appraise_taste_score, " +
                    " ifnull(ROUND( AVG( b.appraise_pack_score ), 1 ),8) appraise_pack_score, " +
                    " ifnull(round(SUM( CASE WHEN b.appraise_score > 6 THEN b.appraise_score ELSE 0 END )/ SUM( b.appraise_score ) * 100,0 ),80) good_rate " +
                    "FROM " +
                    " partner a " +
                    " LEFT JOIN ( " +
                    " SELECT " +
                    "  *  " +
                    " FROM " +
                    "  appraise_log  " +
                    " WHERE " +
                    " partner_id = ?) b ON a.partner_id = b.partner_id  " +
                    "WHERE " +
                    " a.partner_id = ?  " +
                    "GROUP BY " +
                    " a.partner_name";
            sqlReady = new SQLReady(sql,queryParamsShopInfo.getPartnerId(),queryParamsShopInfo.getPartnerId());
        }else if(queryParamsShopInfo.getBranchId() != null){
            sql = "SELECT " +
                    " a.branch_id , " +
                    " null partner_id, " +
                    " a.branch_name shop_name, " +
                    " a.branch_head_img shop_img, " +
                    " ifnull(ROUND( AVG( b.appraise_score ), 1 ),8) score, " +
                    " ifnull(ROUND( AVG( b.appraise_taste_score ), 1 ),8) appraise_taste_score, " +
                    " ifnull(ROUND( AVG( b.appraise_pack_score ), 1 ),8) appraise_pack_score, " +
                    " ifnull(round(SUM( CASE WHEN b.appraise_score > 6 THEN b.appraise_score ELSE 0 END )/ SUM( b.appraise_score ) * 100,0 ),80) good_rate " +
                    "FROM " +
                    " branch a " +
                    " LEFT JOIN ( SELECT * FROM appraise_log WHERE branch_id = ? AND partner_id IS NULL ) b ON a.branch_id = b.branch_id  " +
                    "WHERE " +
                    " a.branch_id = ?  " +
                    "GROUP BY " +
                    " a.branch_name";

            sqlReady = new SQLReady(sql,queryParamsShopInfo.getBranchId(),queryParamsShopInfo.getBranchId());
        }

        List<Map> query =sqlManager.execute(sqlReady,Map.class);



        return ResultUtil.success(query.get(0) == null ? null:query.get(0));
    }

    public Result shopInfoGoodsTypes(QueryParamsShopInfo queryParamsShopInfo) {
        if(queryParamsShopInfo.getBranchId() == null && queryParamsShopInfo.getPartnerId() == null){
            return ResultUtil.error(-1,"店面id缺失");
        }

        String sql = "";
        SQLReady sqlReady = null;
        if(queryParamsShopInfo.getPartnerId() != null){
            //查询该分店下有的主营类别
            sql = "SELECT " +
                    " b.major_type_id, " +
                    " b.major_name  " +
                    "FROM " +
                    " major_branch_partner a " +
                    " LEFT JOIN major_type b ON a.major_type_id = b.major_type_id  " +
                    "WHERE " +
                    " a.partner_id = ?  ";
            sqlReady = new SQLReady(sql,queryParamsShopInfo.getPartnerId());
            List<MajorTypeInfo> majorTypeInfos =sqlManager.execute(sqlReady,MajorTypeInfo.class);
            if(majorTypeInfos == null || majorTypeInfos.size() == 0){
                throw new MyException(-1,"主营类别未初始化");
            }

            //查询该分店下所有商品
            String sql1 = "SELECT " +
                    " a.*, " +
                    " b.goods_model_id, " +
                    " b.goods_model_name, " +
                    " b.goods_total, " +
                    " MIN(b.goods_model_cost) goods_model_cost, " +
                    " MIN(b.goods_model_sale_price) goods_model_sale_price, " +
                    " MIN(b.goods_model_source_price) goods_model_source_price, " +
                    " MIN(b.goods_model_channel_price) goods_model_channel_price " +
                    "FROM " +
                    " goods_def a " +
                    " LEFT JOIN goods_model b ON a.goods_def_id = b.goods_def_id  " +
                    "WHERE " +
                    " a.partner_id = ?  " +
                    " AND a.STATUS = 1 and a.goods_def_id not in (select goods_def_id from activity_goods) " +
                    " AND b.STATUS = 1 group by a.goods_def_id";
            SQLReady sqlReady1 = new SQLReady(sql1,queryParamsShopInfo.getPartnerId());
            List<GoodsDefModel> goodsDefs =sqlManager.execute(sqlReady1,GoodsDefModel.class);

            //根据该分店下有的主营类别，将商品分类整理好
            majorTypeInfos.forEach(majorTypeInfo -> {
                Set<GoodsDefModel> goodsDefModels = new HashSet<>();
                if(goodsDefs == null || goodsDefs.size() == 0){
                    throw new MyException(-1,"该店没有商品上架");
                }
                goodsDefs.forEach(goodsDef -> {
                    if(StringUtils.isEmpty(goodsDef.getGoodsMajorType())){
                        throw new MyException(-1,"商品类别不存在");
                    }
                    JSONArray typeids=  JSONArray.parseArray(goodsDef.getGoodsMajorType());
                    if(typeids.stream().anyMatch(typeid -> {
                        return typeid.toString().equals(majorTypeInfo.getMajorTypeId().toString());
                    })){
                        goodsDefModels.add(goodsDef);
                    }

                });
                majorTypeInfo.setGoodsDefList(goodsDefModels);
            });

            return ResultUtil.success(majorTypeInfos);
        }else if(queryParamsShopInfo.getBranchId() != null){
            //查询该主店下有的主营类别
            sql = "SELECT " +
                    " b.major_type_id, " +
                    " b.major_name  " +
                    "FROM " +
                    " major_branch_partner a " +
                    " LEFT JOIN major_type b ON a.major_type_id = b.major_type_id  " +
                    "WHERE " +
                    " a.branch_id = ?  " +
                    " AND a.partner_id IS NULL";
            sqlReady = new SQLReady(sql,queryParamsShopInfo.getBranchId());
            List<MajorTypeInfo> majorTypeInfos =sqlManager.execute(sqlReady,MajorTypeInfo.class);
            if(majorTypeInfos == null || majorTypeInfos.size() == 0){
                throw new MyException(-1,"主营类别未初始化");
            }

            //查询该主店下所有商品
            String sql1 = "SELECT " +
                    " a.*, " +
                    " b.goods_model_id, " +
                    " b.goods_model_name, " +
                    " b.goods_total, " +
                    " MIN(b.goods_model_cost) goods_model_cost, " +
                    " MIN(b.goods_model_sale_price) goods_model_sale_price, " +
                    " MIN(b.goods_model_source_price) goods_model_source_price, " +
                    " MIN(b.goods_model_channel_price) goods_model_channel_price " +
                    "FROM " +
                    " goods_def a " +
                    " LEFT JOIN goods_model b ON a.goods_def_id = b.goods_def_id  " +
                    "WHERE " +
                    " a.branch_id = ?  " +
                    " AND a.partner_id IS NULL  " +
                    " AND a.STATUS = 1  " +
                    " AND b.STATUS = 1  and a.goods_def_id not in (select goods_def_id from activity_goods ) " +
                    " group by a.goods_def_id";
            SQLReady sqlReady1 = new SQLReady(sql1,queryParamsShopInfo.getBranchId());
            List<GoodsDefModel> goodsDefs =sqlManager.execute(sqlReady1,GoodsDefModel.class);

            //根据该主店下有的主营类别，将商品分类整理好
            majorTypeInfos.forEach(majorTypeInfo -> {
                Set<GoodsDefModel> goodsDefModels = new HashSet<>();
                if(goodsDefs == null || goodsDefs.size() == 0){
                    throw new MyException(-1,"该店没有商品上架");
                }
                goodsDefs.forEach(goodsDef -> {
                    if(StringUtils.isEmpty(goodsDef.getGoodsMajorType())){
                        throw new MyException(-1,"商品类别不存在");
                    }
                    JSONArray typeids=  JSONArray.parseArray(goodsDef.getGoodsMajorType());
                    if(typeids.stream().anyMatch(typeid -> {
                        return typeid.toString().equals(majorTypeInfo.getMajorTypeId().toString());
                    })){
                        goodsDefModels.add(goodsDef);
                    }

                });
                majorTypeInfo.setGoodsDefList(goodsDefModels);
            });

            return ResultUtil.success(majorTypeInfos);
        }
        return null;
    }

    public Result shopAppraiseList(QueryParamsShopGoodsAppraise queryParamsShopGoodsAppraise) {
        if(queryParamsShopGoodsAppraise.getPage() == null || queryParamsShopGoodsAppraise.getLimit() == null){
            return ResultUtil.error(-1,"缺少分页参数");
        }
        if(queryParamsShopGoodsAppraise.getPartnerId() != null){
            //分店
            String typeSql = "";
            //评价类型，1-全部，2-有图，3-普通点评
            if(queryParamsShopGoodsAppraise.getType() == null || queryParamsShopGoodsAppraise.getType().intValue() == 1){
                typeSql = "";
            }else if(queryParamsShopGoodsAppraise.getType() != null && queryParamsShopGoodsAppraise.getType().intValue() == 2){
                typeSql = " and a.appraise_pic is not null and LENGTH(trim(a.appraise_pic))>0 ";
            }else if(queryParamsShopGoodsAppraise.getType() != null && queryParamsShopGoodsAppraise.getType().intValue() == 3){
                typeSql = " and (a.partner_id = " + queryParamsShopGoodsAppraise.getPartnerId() + " and a.appraise_pic IS NULL OR LENGTH(trim( a.appraise_pic ))= 0 ) ";
            }
            String sql = "select * from (SELECT " +
                    " a.*, " +
                    " b.we_chat_user_info_id, " +
                    " b.nickname, " +
                    " b.headimgurl  " +
                    "FROM " +
                    " appraise_log a " +
                    " LEFT JOIN ( SELECT we_chat_user_info_id, unionid, nickname, headimgurl FROM we_chat_user_info GROUP BY unionid ) b ON a.unionid = b.unionid where a.partner_id = ?  " +
                    typeSql +
                    " ORDER BY " +
                    " a.create_time desc) main";

            SQLReady sqlReady = new SQLReady(sql,queryParamsShopGoodsAppraise.getPartnerId());

            PageQuery<AppraiseLog> pageQuery = new PageQuery<AppraiseLog>(queryParamsShopGoodsAppraise.getPage().longValue(),queryParamsShopGoodsAppraise.getLimit().longValue());
            PageQuery<AppraiseLog> query =sqlManager.execute(sqlReady,AppraiseLog.class,pageQuery);
            return ResultUtil.success(query.getList(),query.getTotalRow());
        }else if(queryParamsShopGoodsAppraise.getBranchId() != null){
            //主店
            String typeSql = "";
            //评价类型，1-全部，2-有图，3-普通点评
            if(queryParamsShopGoodsAppraise.getType() == null || queryParamsShopGoodsAppraise.getType().intValue() == 1){
                typeSql = "";
            }else if(queryParamsShopGoodsAppraise.getType() != null && queryParamsShopGoodsAppraise.getType().intValue() == 2){
                typeSql = " and a.appraise_pic is not null and LENGTH(trim(a.appraise_pic))>0 ";
            }else if(queryParamsShopGoodsAppraise.getType() != null && queryParamsShopGoodsAppraise.getType().intValue() == 3){
                typeSql = " and (a.branch_id = " + queryParamsShopGoodsAppraise.getBranchId() + " and a.appraise_pic IS NULL OR LENGTH(trim( a.appraise_pic ))= 0 ) ";
            }
            String sql = "select * from (SELECT " +
                    " a.*, " +
                    " b.we_chat_user_info_id, " +
                    " b.nickname, " +
                    " b.headimgurl  " +
                    "FROM " +
                    " appraise_log a " +
                    " LEFT JOIN ( SELECT we_chat_user_info_id, unionid, nickname, headimgurl FROM we_chat_user_info GROUP BY unionid ) b ON a.unionid = b.unionid where a.branch_id = ? and partner_id is null " +
                    typeSql +
                    " ORDER BY " +
                    " a.create_time desc) main";

            SQLReady sqlReady = new SQLReady(sql,queryParamsShopGoodsAppraise.getBranchId());

            PageQuery<AppraiseLog> pageQuery = new PageQuery<AppraiseLog>(queryParamsShopGoodsAppraise.getPage().longValue(),queryParamsShopGoodsAppraise.getLimit().longValue());
            PageQuery<AppraiseLog> query =sqlManager.execute(sqlReady,AppraiseLog.class,pageQuery);
            return ResultUtil.success(query.getList(),query.getTotalRow());
        }
        return null;
    }

    public Result getBuyCarInfo(HttpServletRequest request, QueryParamsBuyCarInfo buyCarInfo) {
        //buyCarInfo.setPage(1);
        //buyCarInfo.setLimit(10);
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();//"1";
        String paramLongitude = buyCarInfo.getLongitude();//"120.463097";
        String paramLatitude = buyCarInfo.getLatitude();//"27.781187";
        LocationPoint point = new LocationPoint(Double.parseDouble(paramLongitude),Double.parseDouble(paramLatitude));
        paramLongitude = LocationUtils.gcj02_To_Wgs84(point).getLongitude().toString();
        paramLatitude = LocationUtils.gcj02_To_Wgs84(point).getLatitude().toString();

        //取购物车所有产品按时间排序的店铺id
        SQLReady sqlBranchPartnerNo = new SQLReady(
                "select CONCAT(ifnull(b.branch_id,0),'-',IfNULL(p.partner_id,0)) branchPartnerIds " +
                "                from   " +
                "                buy_car_log bcl left join goods_def gd on bcl.goods_def_id = gd.goods_def_id  " +
                "                left join goods_model gm on bcl.goods_model_id = gm.goods_model_id   " +
                "                left join branch b on gd.branch_id = b.branch_id   " +
                "                left join partner p on p.partner_id = gd.partner_id   " +
                "                where bcl.status = 1   " +
                "                and bcl.unionid = ? " +
                "group by b.branch_id , p.partner_id order by max(bcl.create_time) desc ",unionid );
        //PageQuery pageQuery = new PageQuery<Map>(buyCarInfo.getPage(),buyCarInfo.getLimit());
        //PageQuery query = sqlManager.execute(sqlBranchPartnerNo,  Map.class,pageQuery);
        //query.getList();
        List<Map> list = sqlManager.execute(sqlBranchPartnerNo,  Map.class);
        //通过店铺id将收藏的产品按时间降序排序
        String sqlBranchPartnerNoStr = "" ;
        for(Map map : list){
            sqlBranchPartnerNoStr+=map.get("branchPartnerIds")+",";
        }
        if(sqlBranchPartnerNoStr.length() == 0 ){
            return ResultUtil.success(null);
        }
        sqlBranchPartnerNoStr = sqlBranchPartnerNoStr.substring(0,sqlBranchPartnerNoStr.length()-1);
        //按店铺id分组显示
        SQLReady sql = new SQLReady(
                "select * from (select " +
                "bcl.buy_car_log_id," +
                "bcl.buy_count," +
                "bcl.create_time, " +
                "case when p.partner_name is not null then p.partner_name else b.branch_name end as StoreName, " +
                "case when p.partner_name is not null " +
                        "then st_distance_sphere(point(p.longitude_wgs,p.latitude_wgs) , point(?,?)) " +
                        "else st_distance_sphere(point(b.longitude_wgs,b.latitude_wgs) , point(?,?)) end as distances, " +
                "gd.goods_pic," +
                "gd.goods_def_id," +
                "gd.buy_method," +
                "gd.goods_name," +
                "gm.goods_model_name," +
                "gm.goods_model_id," +
                "gm.goods_model_sale_price," +
                "gm.goods_total," +
                "vsi.stockCount," +
                "vsi.salesCount," +
                "gm.status ," +
                "b.branch_id," +
                "p.partner_id," +
                "find_in_set(concat(ifnull(b.branch_id,0),'-',ifnull(p.partner_id,0)),?) as findInSetSort " +
                "from " +
                "buy_car_log bcl left join goods_def gd on bcl.goods_def_id = gd.goods_def_id " +
                "left join goods_model gm on bcl.goods_model_id = gm.goods_model_id " +
                "left join branch b on gd.branch_id = b.branch_id " +
                "left join partner p on p.partner_id = gd.partner_id " +
                "left join view_stock_info vsi on gm.goods_model_id = vsi.goods_model_id " +
                "where bcl.status = 1 " +
                "and bcl.unionid = ? ) t " +
                "where t.findInSetSort > 0 " +
                "order by t.findInSetSort desc  ", paramLongitude,paramLatitude,paramLongitude,paramLatitude,sqlBranchPartnerNoStr , unionid) ;
        List<ReturnParamsBuyCarInfo> returnParamsBuyCarInfos = sqlManager.execute(sql,  ReturnParamsBuyCarInfo.class);
        Map<Integer,List<ReturnParamsBuyCarInfo>> ret = returnParamsBuyCarInfos.stream().collect(Collectors.groupingBy(ReturnParamsBuyCarInfo::getFindInSetSort));

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows",ret);
        jsonObject.put("total",list.size());//query.getTotalRow()
        return ResultUtil.success(jsonObject);
    }

    public Result getGoodsModelByDefId(QueryParamsGetGoodsModels queryParamsGetGoodsModels) {
        String sql = "SELECT * FROM goods_def where goods_def_id = ? and status = 1";
        SQLReady sqlReady = new SQLReady(sql,queryParamsGetGoodsModels.getGoodsDefId());
        List<GoodsDefModelList> list = sqlManager.execute(sqlReady,GoodsDefModelList.class);
        if(list.size() > 0){
            String sql1 = "SELECT gm.*,vsi.salesCount,vsi.stockCount " +
                    "FROM goods_model gm " +
                    "left join view_stock_info vsi on gm.goods_model_id = vsi.goods_model_id " +
                    "where " +
                    "gm.goods_def_id = ? " +
                    "and gm.status = 1 " +
                    "order by gm.goods_model_sale_price ";
            SQLReady sqlReady1 = new SQLReady(sql1,queryParamsGetGoodsModels.getGoodsDefId());
            List<GoodsModel> list1 = sqlManager.execute(sqlReady1,GoodsModel.class);
            list.get(0).setGoodsModelList(list1);
        }
        return ResultUtil.success(list.size() > 0?list.get(0):null);
    }

    public Result saveSearchLog(SearchLog searchLog, HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        searchLog.setCreateTime(new Date());
        searchLog.setOpenid(sessionInfo.getWeChatUserInfo().getOpenid());
        searchLog.setUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
        searchLog.setStatus(1);
        searchLogService.save(searchLog);
        return ResultUtil.success("保存成功");
    }

    public Result getSearchLog(HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        JSONObject ret = new JSONObject();
        List<SearchLog> list = searchLogDao.createLambdaQuery()
                .andEq("unionid",sessionInfo.getWeChatUserInfo().getUnionid())
                .andEq("status" , "1")
                .appendSql(" order by create_time desc ")
                .limit(1,10).select();

        List<SearchLog> listMost = searchLogDao.createLambdaQuery()
                .appendSql("where create_time > date_sub(curdate(), INTERVAL 10 DAY) " +
                           "group by search_content order by count(1) desc ")
                .limit(1,10).select();

        ret.put("mineSearchLog",list);
        ret.put("listMost",listMost);
        return ResultUtil.success(ret);

    }

    public Result goodsTypes() {
        String sql = "select * from major_type where status = 1";
        SQLReady sqlReady = new SQLReady(sql);
        List<MajorType> list = sqlManager.execute(sqlReady,MajorType.class);
        return ResultUtil.success(list);
    }

    public Result getGoodsListBygoodsTypeId(QueryParamsGetGoodsListByTypeId queryParamsGetGoodsListByTypeId) {
        if(queryParamsGetGoodsListByTypeId.getPage() == null || queryParamsGetGoodsListByTypeId.getLimit() == null){
            return ResultUtil.error(-1,"缺少分页参数");
        }
        if(queryParamsGetGoodsListByTypeId.getMajorTypeId() == null){
            return ResultUtil.error(-1,"缺少分类id");
        }
        //根据根据商品分类id分页查询商品
        String sql = "SELECT " +
                " *  " +
                "FROM " +
                " ( " +
                " SELECT " +
                "  a.*,  " +
                "  b.goods_model_id, " +
                "  b.goods_model_name, " +
                "  b.goods_total, " +
                "  b.goods_model_cost, " +
                "  b.goods_model_sale_price, " +
                "  b.goods_model_channel_price, " +
                "  b.goods_model_source_price  " +
                " FROM " +
                "  goods_def a " +
                "  LEFT JOIN ( " +
                "  SELECT " +
                "   goods_model_id, " +
                "   goods_def_id, " +
                "   goods_model_name, " +
                "   goods_total, " +
                "   goods_model_cost, " +
                "   MIN( goods_model_sale_price ) goods_model_sale_price, " +
                "   goods_model_channel_price, " +
                "   MAX( goods_model_source_price ) goods_model_source_price  " +
                "  FROM " +
                "   goods_model  " +
                "  WHERE " +
                "   STATUS = 1 " +
                "  GROUP BY " +
                "   goods_def_id  " +
                "  ) b ON a.goods_def_id = b.goods_def_id  " +
                " WHERE " +
                "  a.STATUS = 1  and a.goods_def_id not in (select goods_def_id from activity_goods )" +
                "  AND FIND_IN_SET( " +
                "   ?, " +
                "  REPLACE ( REPLACE ( a.goods_major_type, '[', '' ), ']', '' )) != 0  " +
                " ) main";

        SQLReady sqlReady = new SQLReady(sql,queryParamsGetGoodsListByTypeId.getMajorTypeId().toString());

        PageQuery<Map> pageQuery = new PageQuery<Map>(queryParamsGetGoodsListByTypeId.getPage().longValue(),queryParamsGetGoodsListByTypeId.getLimit().longValue());
        PageQuery<Map> query =sqlManager.execute(sqlReady,Map.class,pageQuery);

        //查询每个商品的规格，并放入对象返回
        if(query.getList().size() > 0 ){
            query.getList().forEach(map -> {
                String sql1 = "select * from goods_model where status = 1 and goods_def_id = ?";
                SQLReady sqlReady1 = new SQLReady(sql1,Integer.parseInt(map.get("goodsDefId").toString()));
                List<GoodsModel> list = sqlManager.execute(sqlReady1,GoodsModel.class);
                map.put("modelList",list);
            });
        }

        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    @Transactional
    public Result delSearchLog(HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String sql1 = "update search_log set status = 0 where unionid = ?";
        SQLReady sqlReady1 = null;
        if(sessionInfo.getWeChatUserInfo().getUnionid() != null){
            sqlReady1 = new SQLReady(sql1,sessionInfo.getWeChatUserInfo().getUnionid());
        }else{
            sqlReady1 = new SQLReady(sql1,sessionInfo.getWeChatUserInfo().getOpenid());
        }

        sqlManager.executeUpdate(sqlReady1);
        return ResultUtil.success();
    }

    public Result getGoodsListBygoodsName(QueryParamsGetGoodsListByGoodsName queryParamsGetGoodsListByGoodsName , HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        if(queryParamsGetGoodsListByGoodsName.getPage() == null || queryParamsGetGoodsListByGoodsName.getLimit() == null){
            return ResultUtil.error(-1,"缺少分页参数");
        }
        //根据根据商品分类id分页查询商品
        String sql = " " +
                " SELECT " +
                "  a.*, " +
                "  b.goods_model_id, " +
                "  b.goods_model_name, " +
                "  b.goods_total, " +
                "  b.goods_model_cost, " +
                "  b.goods_model_sale_price, " +
                "  b.goods_model_channel_price, " +
                "  b.goods_model_source_price  " +
                " FROM " +
                "  goods_def a " +
                "  LEFT JOIN ( " +
                "  SELECT " +
                "   goods_model_id, " +
                "   goods_def_id, " +
                "   goods_model_name, " +
                "   goods_total, " +
                "   goods_model_cost, " +
                "   MIN( goods_model_sale_price ) goods_model_sale_price, " +
                "   goods_model_channel_price, " +
                "   MAX( goods_model_source_price ) goods_model_source_price  " +
                "  FROM " +
                "   goods_model  " +
                "  WHERE " +
                "   STATUS = 1  " +
                "  GROUP BY " +
                "   goods_def_id  " +
                "  ) b ON a.goods_def_id = b.goods_def_id  " +
                " WHERE " +
                "  a.STATUS = 1 AND a.goods_def_id NOT IN ( SELECT goods_def_id FROM activity_goods WHERE NOW() > activity_start_time AND NOW() < activity_end_time AND STATUS = 1 ) " +
                (StringUtils.isEmpty(queryParamsGetGoodsListByGoodsName.getGoodsName())?" ":"and a.goods_name like '%" + queryParamsGetGoodsListByGoodsName.getGoodsName() + "%'") ;
                if(queryParamsGetGoodsListByGoodsName.getPartnerId()!=null){
                    sql+=" and a.partner_id = " + queryParamsGetGoodsListByGoodsName.getPartnerId() ;
                }else if(queryParamsGetGoodsListByGoodsName.getBranchId()!=null && queryParamsGetGoodsListByGoodsName.getPartnerId()==null){
                    sql+=" and a.branch_id = " + queryParamsGetGoodsListByGoodsName.getBranchId() +" and isnull(a.partner_id)  " ;
                }else{

                }
        SQLReady sqlReady = new SQLReady(sql);

        PageQuery<Map> pageQuery = new PageQuery<Map>(queryParamsGetGoodsListByGoodsName.getPage().longValue(),queryParamsGetGoodsListByGoodsName.getLimit().longValue());
        PageQuery<Map> query =sqlManager.execute(sqlReady,Map.class,pageQuery);

        //查询每个商品的规格，并放入对象返回
        if(query.getList().size() > 0 ){
            query.getList().forEach(map -> {
                String sql1 = "select * from goods_model where status = 1 and goods_def_id = ?";
                SQLReady sqlReady1 = new SQLReady(sql1,Integer.parseInt(map.get("goodsDefId").toString()));
                List<GoodsModel> list = sqlManager.execute(sqlReady1,GoodsModel.class);
                map.put("modelList",list);
            });
        }
        //存入查询日志表
        SearchLog searchLog = new SearchLog();
        searchLog.setStatus(1);
        searchLog.setUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
        searchLog.setOpenid(sessionInfo.getWeChatUserInfo().getOpenid());
        searchLog.setCreateTime(new Date());
        searchLog.setSearchContent(queryParamsGetGoodsListByGoodsName.getGoodsName());
        searchLogDao.insert(searchLog);
        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    public Result noticeTipList(QueryParamsLong queryParams, HttpServletRequest request) {
        if(queryParams.getPage() == null || queryParams.getLimit() == null){
            return ResultUtil.error(-1,"缺少分页参数");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String sql = "select * from (SELECT " +
                " a.*, " +
                " DATE_FORMAT( a.create_time, '%Y年%m月%d日 %H:%i' ) format_date, " +
                "IF " +
                " ( b.notice_tip_log_id IS NULL, 0, 1 ) is_looked  " +
                "FROM " +
                " notice_tip a " +
                " LEFT JOIN ( SELECT * FROM notice_tip_log WHERE unionid = ? ) b ON a.notice_tip_id = b.notice_tip_id  " +
                "ORDER BY " +
                " a.create_time DESC) main";

        SQLReady sqlReady = new SQLReady(sql,sessionInfo.getWeChatUserInfo().getUnionid());
        PageQuery<Map> pageQuery = new PageQuery<Map>(queryParams.getPage().longValue(),queryParams.getLimit().longValue());
        PageQuery<Map> query =sqlManager.execute(sqlReady,Map.class,pageQuery);
        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    public Result noticeTipLooked( NoticeTipLogSave noticeTipLog,HttpServletRequest request) {
        if(noticeTipLog.getNoticeTipId() == null){
            return ResultUtil.error(-1,"缺少公告id");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);

        List<NoticeTipLog> noticeTipLogs = noticeTipLogDao.execute("select * from notice_tip_log where notice_tip_id = ? and unionid = ?",noticeTipLog.getNoticeTipId(),sessionInfo.getWeChatUserInfo().getUnionid());
        if(noticeTipLogs.size() > 0){
            return ResultUtil.error(-1,"已经查看过了");
        }else{
            NoticeTipLog noticeTipLog1 = new NoticeTipLog();
            noticeTipLog1.setCreateTime(new Date());
            noticeTipLog1.setNoticeTipId(noticeTipLog.getNoticeTipId());
            noticeTipLog1.setOpenid(sessionInfo.getWeChatUserInfo().getOpenid() == null?"":sessionInfo.getWeChatUserInfo().getOpenid());
            noticeTipLog1.setUnionid(sessionInfo.getWeChatUserInfo().getUnionid() == null?"":sessionInfo.getWeChatUserInfo().getUnionid());
            noticeTipLogDao.insert(noticeTipLog1);
            return ResultUtil.success();
        }
    }

    public Result getUnionLinkUserCode(HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String code = "getUnionLinkUserCode_"+sessionInfo.getUserId()+ RandomUtils.getRandNumByLength(5);
        redisTemplate.opsForValue().set(code,code,5, TimeUnit.MINUTES);
        return ResultUtil.success(code);
    }

    public Result oneYuanList(QueryParams queryParams) {
        String sql = " select * from ( " +
                " SELECT " +
                " a.activity_goods_id, " +
                " a.activity_type_id, " +
                " a.goods_def_id, " +
                " a.status, " +
                " DATE_FORMAT( a.activity_start_time, '%m-%d %H:%i:%s' ) activity_start_time, " +
                " DATE_FORMAT( a.activity_end_time, '%m-%d %H:%i:%s' ) activity_end_time, " +
                " b.goods_name, " +
                " b.goods_pic, " +
                "IF " +
                " ( c.activity_price IS NULL, 1, c.activity_price ) activity_price, " +
                " '进行中' time_type ," +
                " 1 as sortTimeType " +
                "FROM " +
                " activity_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id " +
                " LEFT JOIN view_max_one_yuan_price c ON a.goods_def_id = c.goods_def_id  " +
                " AND c.activity_type_id = a.activity_type_id  " +
                "WHERE " +
                " a.activity_type_id = 3  " +
                " AND b.STATUS = 1  " +
                " AND now() > a.activity_start_time  " +
                " AND NOW() < activity_end_time " +
                " union all  " +
                " SELECT " +
                " a.activity_goods_id, " +
                " a.activity_type_id, " +
                " a.goods_def_id, " +
                " a.status, " +
                " DATE_FORMAT( a.activity_start_time, '%m-%d %H:%i:%s' ) activity_start_time, " +
                " DATE_FORMAT( a.activity_end_time, '%m-%d %H:%i:%s' ) activity_end_time, " +
                " b.goods_name, " +
                " b.goods_pic, " +
                "IF " +
                " ( c.activity_price IS NULL, 1, c.activity_price ) activity_price, " +
                " '未开始' time_type ," +
                " 2 as sortTimeType " +
                "FROM " +
                " activity_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id " +
                " LEFT JOIN view_max_one_yuan_price c ON a.goods_def_id = c.goods_def_id  " +
                " AND c.activity_type_id = a.activity_type_id  " +
                "WHERE " +
                " a.activity_type_id = 3  " +
                " AND b.STATUS = 1  " +
                " AND now() < a.activity_start_time  " +
                " union all  " +
                " SELECT " +
                " a.activity_goods_id, " +
                " a.activity_type_id, " +
                " a.goods_def_id, " +
                " a.status, " +
                " DATE_FORMAT( a.activity_start_time, '%m-%d %H:%i:%s' ) activity_start_time, " +
                " DATE_FORMAT( a.activity_end_time, '%m-%d %H:%i:%s' ) activity_end_time, " +
                " b.goods_name, " +
                " b.goods_pic, " +
                "IF " +
                " ( c.activity_price IS NULL, 1, c.activity_price ) activity_price, " +
                " '已结束' time_type , " +
                " 3 as sortTimeType " +
                "FROM " +
                " activity_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id " +
                " LEFT JOIN view_max_one_yuan_price c ON a.goods_def_id = c.goods_def_id  " +
                " AND c.activity_type_id = a.activity_type_id  " +
                "WHERE " +
                " a.activity_type_id = 3  " +
                " AND b.STATUS = 1  " +
                " AND now() > a.activity_end_time  " +
                " ) main order by main.sortTimeType , activity_end_time desc ";
        SQLReady sqlReady = new SQLReady(sql);

        PageQuery<Map> pageQuery = new PageQuery<Map>(queryParams.getPage(),queryParams.getLimit());
        PageQuery<Map> query =sqlManager.execute(sqlReady,Map.class,pageQuery);
        return ResultUtil.success(query.getList(),query.getTotalRow());

    }

    public Result oneYuanGoodsInfo(QueryParamsOneYuan queryParams , HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        if(queryParams.getGoodsDefId() == null){
            return ResultUtil.error(-1,"商品id缺失");
        }
        String sql = "SELECT " +
                " a.*, " +
                " b.goods_pic, " +
                " b.goods_name, " +
                " d.goods_model_source_price, " +
                " b.goods_description, " +
                " b.goods_tips, " +
                "IF " +
                " ( c.activity_price IS NULL, 1, c.activity_price ) activity_price , " +
                " d.goods_model_id ," +
                " b.branch_id, " +
                " b.partner_id, " +
                " ifnull(oi.should_pay_price , 0) = 1 as pay_one_yuan ," +
                " case when ifnull(oii.should_pay_price , 0) > 0 then 1 else 0 end as pay_one_yuan_last " +
                "FROM " +
                " activity_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id " +
                " LEFT JOIN ( SELECT * FROM activity_log WHERE goods_def_id = ? AND activity_type_id = 3 AND STATUS = 1 ORDER BY create_time DESC LIMIT 1 ) c ON a.goods_def_id = c.goods_def_id  " +
                " left join (select * from goods_model where goods_def_id = ? and status = 1 limit 1) d on a.goods_def_id = d.goods_def_id " +
                //查询是否支付一元参与活动
                " left join order_info oi " +
                "   on oi.goods_model_id = d.goods_model_id " +
                "   and oi.status = 1 and oi.source_sub='YDDD' and oi.buyer_unionid = ? " +
                " left join order_info oii " +
                "   on oii.goods_model_id = d.goods_model_id " +
                "   and oii.status = 1  and oii.buyer_unionid = ? " +
                "WHERE " +
                " a.activity_type_id = 3  " +
                " AND a.goods_def_id = ?  " +
                " AND a.STATUS = 1";
        SQLReady sqlReady = new SQLReady(sql,queryParams.getGoodsDefId(),queryParams.getGoodsDefId(),sessionInfo.getWeChatUserInfo().getUnionid() , sessionInfo.getWeChatUserInfo().getUnionid() ,queryParams.getGoodsDefId() );

        List<Map> query =sqlManager.execute(sqlReady,Map.class);
        return ResultUtil.success(query.size() == 0?null:query.get(0));
    }

    @Transactional
    public Result oneYuanGoodsLogAdd(ActivityLog activityLog, HttpServletRequest request) {
        if(activityLog.getActivityPrice() == null){
            return ResultUtil.error(-1,"拍卖价格缺失");
        }
        if(activityLog.getGoodsDefId() == null){
            return ResultUtil.error(-1,"商品id缺失");
        }
        if(activityLog.getGoodsModelId() == null){
            return ResultUtil.error(-1,"商品规格缺失");
        }
        //redis加锁,抢锁等待时间比较重要，过期时间不重要
        String identifier =  redisUtil.lockWithTimeout("yiyuanpaimai" + activityLog.getGoodsDefId(),6000,10000);

        //判断活动是否过期
        String sql11 = "select * from activity_goods where goods_def_id = ? and now() > activity_end_time";
        SQLReady sqlReady11 = new SQLReady(sql11,activityLog.getGoodsDefId());
        List<ActivityGoods> activityGoods = sqlManager.execute(sqlReady11,ActivityGoods.class);
        if(activityGoods.size() > 0){
            return ResultUtil.error(-1,"商品活动已过期");
        }

        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);

        //判断出价是否是现在最高的，不是则返回
        String sql = "select max(activity_price) activity_price from activity_log where activity_type_id = 3 and goods_def_id = ? and goods_model_id = ? and status = 1";
        SQLReady sqlReady = new SQLReady(sql,activityLog.getGoodsDefId(),activityLog.getGoodsModelId());
        List<Map> maxPrice = sqlManager.execute(sqlReady,Map.class);
        if(maxPrice.size() > 0){
            if(maxPrice.get(0).get("activityPrice") != null){
                Double maxPriceD = Double.parseDouble(maxPrice.get(0).get("activityPrice").toString());
                if(maxPriceD > activityLog.getActivityPrice()){
                    //出价已经不是最高的了
                    return ResultUtil.error(-1,"您的出价已经不是最高啦~");
                }
            }
        }

        //判断出价是否比自己之前出价低或者相等，
        String sql1 = "select max(activity_price) activity_price from activity_log where activity_type_id = 3 and goods_def_id = ? and goods_model_id = ? and player_unionid = ? and status = 1";
        SQLReady sqlReady1 = new SQLReady(sql1,activityLog.getGoodsDefId(),activityLog.getGoodsModelId(),sessionInfo.getWeChatUserInfo().getUnionid());
        List<Map> maxPrice1 = sqlManager.execute(sqlReady1,Map.class);
        if(maxPrice1.size() > 0){
            if(maxPrice1.get(0).get("activityPrice") != null){
                Double maxPriceD = Double.parseDouble(maxPrice1.get(0).get("activityPrice").toString());
                if(activityLog.getActivityPrice().doubleValue() <= maxPriceD.doubleValue()){
                    //出价比自己之前的低或者相等
                    return ResultUtil.error(-1,"出价要比自己最低的高哟~");
                }
            }
        }

        activityLog.setActivityTypeId(3);
        activityLog.setPlayerOpenid(sessionInfo.getWeChatUserInfo().getOpenid());
        activityLog.setPlayerUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
        activityLog.setCreateTime(new Date());
        activityLog.setStatus(1);
        activityLogDao.insert(activityLog);

        //redis解锁
        redisUtil.lockDel("yiyuanpaimai" + activityLog.getGoodsDefId(),identifier);
        return ResultUtil.success();
    }

    public Result oneYuanGoodsLogList(QueryParamsOneYuanLog queryParamsOneYuanLog) {
        if(queryParamsOneYuanLog.getGoodsDefId() == null){
            return ResultUtil.error(-1,"商品id缺失");
        }
        if(queryParamsOneYuanLog.getGoodsModelId() == null){
            return ResultUtil.error(-1,"商品规格缺失");
        }
        if(queryParamsOneYuanLog.getActivityLogId() == null){
            return ResultUtil.error(-1,"竞价日志id缺失，第一次传0");
        }

        String sql = "SELECT " +
                " a.activity_log_id, " +
                " a.activity_type_id, " +
                " a.goods_def_id, " +
                " a.goods_model_id, " +
                " a.activity_price, " +
                " a.sponsor_unionid, " +
                " a.sponsor_openid, " +
                " a.player_unionid, " +
                " a.player_openid, " +
                " DATE_FORMAT( a.create_time, '%m-%d %H:%i:%s' ) create_time, " +
                " a.status , " +
                " b.nickname " +
                "FROM " +
                " activity_log a left join (select * from we_chat_user_info GROUP BY unionid) b on a.player_unionid = b.unionid " +
                "WHERE " +
                " activity_type_id = 3  " +
                " AND goods_def_id = ?  " +
                " AND goods_model_id = ?  " +
                " AND status = 1  " +
                " AND activity_log_id > ?  " +
                "ORDER BY " +
                " create_time DESC";
        SQLReady sqlReady = new SQLReady(sql,queryParamsOneYuanLog.getGoodsDefId(),queryParamsOneYuanLog.getGoodsModelId(),queryParamsOneYuanLog.getActivityLogId());

        List<Map> query =sqlManager.execute(sqlReady,Map.class);

        return ResultUtil.success(query);

    }

    @Transactional
    public Result userBindPhone(WeChatUserInfoDetail weChatUserInfoDetail, HttpServletRequest request) throws Exception{
        if(StringUtils.isEmpty(weChatUserInfoDetail.getPhoneNum())){
            return ResultUtil.error(-1,"手机号为空");
        }
        if(StringUtils.isEmpty(weChatUserInfoDetail.getWeChatUserInfoDetailTag())){
            return ResultUtil.error(-1,"标签为空");
        }
        //验证码是否一致，错误或过期会抛出异常
        if(aliYunSmsUtil.phoneCodeIsPass(weChatUserInfoDetail.getPhoneNum(),weChatUserInfoDetail.getPhoneCode())){
            SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
            weChatUserInfoDetail.setOpenid(sessionInfo.getWeChatUserInfo().getOpenid());
            weChatUserInfoDetail.setUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            WeChatUserInfoDetail detail = weChatUserInfoDetailDao.createLambdaQuery().andEq("unionid",sessionInfo.getWeChatUserInfo().getUnionid()).single();
            if(detail == null){
                weChatUserInfoDetailDao.insert(weChatUserInfoDetail);
            }else{
                //detail.setPhoneNum(weChatUserInfoDetail.getPhoneNum());
                detail.setWeChatUserInfoDetailTag(weChatUserInfoDetail.getWeChatUserInfoDetailTag());
                weChatUserInfoDetailDao.updateById(detail);
            }
        }
        return ResultUtil.success();
    }

    public Result bargainingAndGroupTimes() {
        String sql = "SELECT " +
                " DATE_FORMAT( a.activity_start_time, '%Y-%m-%d %H:%i:%s' ) activity_start_time, " +
                " DATE_FORMAT( max( a.activity_end_time ), '%Y-%m-%d %H:%i:%s' ) activity_end_time, " +
                " DATE_FORMAT( a.activity_start_time, '%H:%i' ) hour_time, " +
                " DATE_FORMAT( a.activity_start_time, '%d日' ) day_time, " +
                "CASE " +
                "  WHEN now() > a.activity_end_time THEN " +
                "  '已结束'  " +
                "  WHEN now() > a.activity_start_time  " +
                "  AND now() < a.activity_end_time THEN " +
                "   '已开启'  " +
                "   WHEN now() < a.activity_start_time THEN " +
                "   '未开启'  " +
                "  END AS time_status  " +
                " FROM " +
                "  activity_goods a  " +
                " WHERE " +
                "  a.status = 1 and a.activity_type_id = 1 or a.activity_type_id = 2 " +
                "  AND DATE_FORMAT( a.activity_start_time, '%Y%m' ) = DATE_FORMAT( now(), '%Y%m' )  " +
                " GROUP BY " +
                "  a.activity_start_time  " +
                " ORDER BY " +
                "  a.activity_start_time";
        SQLReady sqlReady = new SQLReady(sql);

        List<Map> query =sqlManager.execute(sqlReady,Map.class);

        return ResultUtil.success(query);

    }

    public Result bargainingAndGroupGoodsList(QueryParamsBargain queryParamsBargain) {
        if(queryParamsBargain.getPage() == null){
            ResultUtil.error(-1,"分页参数缺失");
        }
        if(queryParamsBargain.getLimit() == null){
            ResultUtil.error(-1,"分页参数缺失");
        }
        if(StringUtils.isEmpty(queryParamsBargain.getActivityStartTime())){
            ResultUtil.error(-1,"筛选时间缺失");
        }
        if(StringUtils.isEmpty(queryParamsBargain.getActivityEndTime())){
            ResultUtil.error(-1,"筛选时间缺失");
        }
        String sql = "select * from ( SELECT " +
                " a.goods_def_id, " +
                " b.goods_name, " +
                " b.goods_pic, " +
                "d.goods_model_sale_price activity_price, " +
                "d.goods_model_source_price, " +
                "IF " +
                " ( a.activity_type_id = 1, '砍价', '拼团' ) type  " +
                "FROM " +
                " activity_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id " +
                " LEFT JOIN goods_model d ON a.goods_def_id = d.goods_def_id where (a.activity_type_id = 1 or a.activity_type_id = 2) and a.activity_start_time >= ? AND a.activity_end_time <= ? ) t";
        SQLReady sqlReady = new SQLReady(sql,queryParamsBargain.getActivityStartTime(),queryParamsBargain.getActivityEndTime());

        PageQuery<Map> pageQuery = new PageQuery<Map>(queryParamsBargain.getPage().longValue(),queryParamsBargain.getLimit().longValue());
        PageQuery<Map> query =sqlManager.execute(sqlReady,Map.class,pageQuery);

        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    public Result bargainingAndGroupGoodsInfo(QueryParamsOneYuan queryParamsOneYuan) {
        if(queryParamsOneYuan.getGoodsDefId() == null){
            ResultUtil.error(-1,"商品id缺失");
        }

        String sql = "SELECT " +
                " DATE_FORMAT( a.activity_start_time, '%Y-%m-%d %H:%i:%s' ) activity_start_time, " +
                " DATE_FORMAT( a.activity_end_time, '%Y-%m-%d %H:%i:%s' ) activity_end_time, " +
                " a.goods_def_id, " +
                " b.goods_name, " +
                " b.goods_pic, " +
                " b.goods_description, " +
                " b.goods_tips, " +
                " d.goods_model_sale_price activity_price, " +
                "IF " +
                " ( a.activity_type_id = 1, '砍价', '拼团' ) type  " +
                "FROM " +
                " activity_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id " +
                " left join goods_model d on a.goods_def_id = d.goods_def_id  " +
                "WHERE " +
                " a.goods_def_id = ?";
        SQLReady sqlReady = new SQLReady(sql,queryParamsOneYuan.getGoodsDefId());
        
        List<Map> query =sqlManager.execute(sqlReady,Map.class);

        return ResultUtil.success(query.size() > 0?query.get(0):null);
    }

    public Result bargaining(QueryParamsBargaining queryParams, HttpServletRequest request) {
        if(queryParams.getGoodsDefId() == null){
            ResultUtil.error(-1,"商品id缺失");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String selfUnionid = sessionInfo.getWeChatUserInfo().getUnionid();
        String sql = "SELECT " +
                " DATE_FORMAT( a.activity_start_time, '%Y-%m-%d %H:%i:%s' ) activity_start_time, " +
                " DATE_FORMAT( a.activity_end_time, '%Y-%m-%d %H:%i:%s' ) activity_end_time, " +
                " a.goods_def_id, " +
                " b.goods_name, " +
                " b.goods_pic, " +
                " b.goods_description, " +
                " b.goods_tips, " +
                " d.goods_model_id, " +
                " d.goods_model_sale_price, " +
                " d.goods_model_source_price, " +
                "IF( c.activity_price IS NULL, d.goods_model_source_price, d.goods_model_source_price - c.activity_price ) activity_price, " +
                "IF( c.activity_price IS NULL, 0, c.activity_price ) discounted_price, " +
                "if(c.activity_price IS NULL,'100%',concat(cast(round((1 - (c.activity_price/(d.goods_model_source_price - d.goods_model_sale_price))) * 100,2) as char),'%')) disparity, " +
                " (SELECT activity_log_id FROM activity_log WHERE status = 1 AND activity_type_id = 1 AND goods_def_id = ? AND sponsor_unionid = ? AND player_unionid = ?) is_in, " +
                " (SELECT count(*) FROM order_info WHERE goods_def_id = ?) saled_count," +
                " case when ifnull(oii.should_pay_price , 0) > 0 then 1 else 0 end as pay_one_yuan_last " +
                "FROM " +
                " activity_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id " +
                " LEFT JOIN ( SELECT goods_def_id, sum( activity_price ) activity_price FROM activity_log WHERE status = 1 AND activity_type_id = 1 AND goods_def_id = ? AND sponsor_unionid = ? ) c ON a.goods_def_id = c.goods_def_id " +
                " LEFT JOIN goods_model d ON a.goods_def_id = d.goods_def_id  " +
                " left join order_info oii " +
                "   on oii.goods_model_id = d.goods_model_id " +
                "   and oii.status = 1  and oii.buyer_unionid = ? " +
                "WHERE " +
                " a.goods_def_id = ?";

        SQLReady sqlReady = null;
        if(StringUtils.isEmpty(queryParams.getSponsorUnionid())){
            //发起人unionid空，说明是查询自己的砍价团
            sqlReady = new SQLReady(sql,queryParams.getGoodsDefId(),selfUnionid,selfUnionid,queryParams.getGoodsDefId(),queryParams.getGoodsDefId(),selfUnionid,selfUnionid , queryParams.getGoodsDefId());
        }else{
            //发起人unionid不为空，说明是查询别人的砍价团，需要计算已砍价金额和差比例
            sqlReady = new SQLReady(sql,queryParams.getGoodsDefId(),queryParams.getSponsorUnionid(),selfUnionid,queryParams.getGoodsDefId(),queryParams.getGoodsDefId(),queryParams.getSponsorUnionid(),selfUnionid , queryParams.getGoodsDefId());
        }
        List<Map> query =sqlManager.execute(sqlReady,Map.class);

        return ResultUtil.success(query.size() > 0?query.get(0):null);
    }

    public Result bargainingList(QueryParamsBargain1 queryParamsBargain1, HttpServletRequest request) {
        if(queryParamsBargain1.getGoodsDefId() == null){
            ResultUtil.error(-1,"商品id缺失");
        }
        if(queryParamsBargain1.getActivityLogId() == null){
            return ResultUtil.error(-1,"竞价日志id缺失，第一次传0");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String sql = "select * from (SELECT " +
                " a.*, " +
                " b.nickname, " +
                " b.headimgurl  " +
                "FROM " +
                " activity_log a " +
                " LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) b ON a.player_unionid = b.unionid  " +
                "WHERE " +
                " a.status = 1  " +
                " AND a.goods_def_id = ?  " +
                " AND a.activity_type_id = 1  " +
                " AND a.activity_log_id > ?  " +
                " and a.sponsor_unionid = ? " +
                "ORDER BY " +
                " a.create_time DESC) t";
        SQLReady sqlReady = new SQLReady(sql,queryParamsBargain1.getGoodsDefId(),queryParamsBargain1.getActivityLogId(),StringUtils.isEmpty(queryParamsBargain1.getSponsorUnionid())?sessionInfo.getWeChatUserInfo().getUnionid():queryParamsBargain1.getSponsorUnionid());

        List<Map> query =sqlManager.execute(sqlReady,Map.class);

        return ResultUtil.success(query);

    }

    @Transactional
    public Result bargainingAdd(QueryParamsBargainAdd queryParamsBargainAdd, HttpServletRequest request) {
        if(queryParamsBargainAdd.getGoodsDefId() == null){
            return ResultUtil.error(-1,"商品id缺失");
        }
        if(queryParamsBargainAdd.getGoodsModelId() == null){
            return ResultUtil.error(-1,"商品规格id缺失");
        }
        //redis加锁,抢锁等待时间比较重要，过期时间不重要
        String identifier =  redisUtil.lockWithTimeout("kanjia" + queryParamsBargainAdd.getGoodsDefId(),6000,10000);

        //判断活动是否过期
        String sql11 = "select * from activity_goods where goods_def_id = ? and now() > activity_end_time";
        SQLReady sqlReady11 = new SQLReady(sql11,queryParamsBargainAdd.getGoodsDefId());
        List<ActivityGoods> activityGoods = sqlManager.execute(sqlReady11,ActivityGoods.class);
        if(activityGoods.size() > 0){
            return ResultUtil.error(-1,"商品活动已过期");
        }

        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
                String sql = "select * from goods_model where goods_model_id = ?";
        SQLReady sqlReady = new SQLReady(sql,queryParamsBargainAdd.getGoodsModelId());
        List<GoodsModel> goodsModels = sqlManager.execute(sqlReady,GoodsModel.class);
        if(goodsModels.size() == 0){
            return ResultUtil.error(-1,"商品规格存在问题");
        }
        ActivityLog activityLog = new ActivityLog();
        //是否是自己砍自己
        if(StringUtils.isEmpty(queryParamsBargainAdd.getSponsorUnionid())){
            //自己砍自己
            //判断是否以及有该商品的砍自己的记录
            String sql1 = "select * from activity_log where status = 1 and activity_type_id = 1 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid = ? and player_unionid = ?";
            SQLReady sqlReady1 = new SQLReady(sql1,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),sessionInfo.getWeChatUserInfo().getUnionid(),sessionInfo.getWeChatUserInfo().getUnionid());
            List<Map> hasSelfList = sqlManager.execute(sqlReady1,Map.class);
            if(hasSelfList.size() > 0){
                return ResultUtil.error(-1,"您已经发起过砍价了");
            }
            //砍价金额生成（ 原价-销售价）* 随机 0.1-1%
            double price = (goodsModels.get(0).getGoodsModelSourcePrice() - goodsModels.get(0).getGoodsModelSalePrice()) * WeightRandomUtil.kanjiaBili();
            //砍价过小，因为保留2位小数所有要放大价格
            if(price < 0.01){
                if(price < 0.001){
                    price = price * 100;
                }else{
                    price = price * 10;
                }
            }

            activityLog.setActivityTypeId(1);
            activityLog.setStatus(1);
            activityLog.setActivityPrice(price);
            activityLog.setGoodsDefId(queryParamsBargainAdd.getGoodsDefId());
            activityLog.setGoodsModelId(queryParamsBargainAdd.getGoodsModelId());
            activityLog.setSponsorUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            activityLog.setSponsorOpenid(StringUtils.isEmpty(sessionInfo.getWeChatUserInfo().getOpenid())?null:sessionInfo.getWeChatUserInfo().getOpenid());
            activityLog.setPlayerOpenid(StringUtils.isEmpty(sessionInfo.getWeChatUserInfo().getOpenid())?null:sessionInfo.getWeChatUserInfo().getOpenid());
            activityLog.setPlayerUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            activityLog.setCreateTime(new Date());
        }else{
            //帮别人砍
            //判断发起人是否已经自己砍过自己，一定要自己砍过自己才能帮团发起人砍
            String sql5 = "select * from activity_log where status = 1 and activity_type_id = 1 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid = ? and player_unionid = ?";
            SQLReady sqlReady5 = new SQLReady(sql5,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),queryParamsBargainAdd.getSponsorUnionid(),queryParamsBargainAdd.getSponsorUnionid());
            List<Map> hasSelfList = sqlManager.execute(sqlReady5,Map.class);
            if(hasSelfList.size() == 0){
                return ResultUtil.error(-1,"您的朋友还未发起砍价活动呢");
            }

            //判断一天内是否已经帮别人砍过的记录，因为限定了一天只能砍一刀，所以单个发起人的砍价就不用去验证是否已经帮他砍过了
            String sql1 = "SELECT * FROM activity_log WHERE DATEDIFF(create_time,NOW()) = 0 and status = 1 and activity_type_id = 1 and sponsor_unionid != ? and player_unionid = ?";
            SQLReady sqlReady1 = new SQLReady(sql1,sessionInfo.getWeChatUserInfo().getUnionid(),sessionInfo.getWeChatUserInfo().getUnionid());
            List<Map> hasHelpList = sqlManager.execute(sqlReady1,Map.class);
            if(hasHelpList.size() > 0){
                return ResultUtil.error(-1,"您今天的砍价次数用完啦");
            }
            //砍价金额生成（ 原价-销售价）* 随机 0.1-1%
            double price = (goodsModels.get(0).getGoodsModelSourcePrice() - goodsModels.get(0).getGoodsModelSalePrice()) * WeightRandomUtil.kanjiaBili();
            //砍价过小，因为保留2位小数所有要放大价格
            if(price < 0.01){
                if(price < 0.001){
                    price = price * 100;
                }else{
                    price = price * 10;
                }
            }
            activityLog.setActivityPrice(price);//可能会被下面的逻辑覆盖金额
            //砍价最低价格不能低于销售价
            String sql3 = "select sum(activity_price) sum_price from activity_log where status = 1 and goods_def_id = ? and goods_model_id = ? and activity_type_id = 1 and sponsor_unionid = ?";
            SQLReady sqlReady3 = new SQLReady(sql3,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),queryParamsBargainAdd.getSponsorUnionid());
            List<Map> sumPrice = sqlManager.execute(sqlReady3,Map.class);
            if(sumPrice.size() > 0){
                if(sumPrice.get(0).get("sumPrice") != null){
                    //现价差 = （原价 - 已经砍了的总和）- 销售价
                    double cha = (goodsModels.get(0).getGoodsModelSourcePrice() - Double.parseDouble(sumPrice.get(0).get("sumPrice").toString())) - goodsModels.get(0).getGoodsModelSalePrice();
                    if(cha <= 0){
                        //已经小于等于销售价了，不能再砍了
                        return ResultUtil.error(-1,"已经是最低价啦");
                    }else{
                        //另外最后一次砍价如果大于剩下的价格空间需要变成剩下的价格
                        //随机价格 > 销售价 - （原件 - 已经砍了的总和）
                        if(price > cha){
                            activityLog.setActivityPrice(cha);//随机金额大于最低差额，覆盖金额
                            //推送砍价成功
                            //查询公众号openid,用于推送
                            SQLReady sqlReadyo = new SQLReady("select * from we_chat_user_info where unionid = ? and source = 1",queryParamsBargainAdd.getSponsorUnionid());
                            List<WeChatUserInfo> weChatUserInfos = sqlManager.execute(sqlReadyo,WeChatUserInfo.class);
                            if(weChatUserInfos.size() > 0){
                                //推送
                                weChatPushMessageUtil.kanjiaSuccess(goodsModels.get(0).getGoodsModelName(),goodsModels.get(0).getGoodsModelSalePrice().toString(),weChatUserInfos.get(0).getOpenid());
                            }
                        }
                        if(price == cha){
                            //推送砍价成功
                            //查询公众号openid,用于推送
                            SQLReady sqlReadyo = new SQLReady("select * from we_chat_user_info where unionid = ? and source = 1",queryParamsBargainAdd.getSponsorUnionid());
                            List<WeChatUserInfo> weChatUserInfos = sqlManager.execute(sqlReadyo,WeChatUserInfo.class);
                            if(weChatUserInfos.size() > 0){
                                //推送
                                weChatPushMessageUtil.kanjiaSuccess(goodsModels.get(0).getGoodsModelName(),goodsModels.get(0).getGoodsModelSalePrice().toString(),weChatUserInfos.get(0).getOpenid());
                            }
                        }
                    }
                }
            }

            activityLog.setActivityTypeId(1);
            activityLog.setStatus(1);
            activityLog.setGoodsDefId(queryParamsBargainAdd.getGoodsDefId());
            activityLog.setGoodsModelId(queryParamsBargainAdd.getGoodsModelId());
            activityLog.setSponsorUnionid(queryParamsBargainAdd.getSponsorUnionid());
            String sql2 = "select * from we_chat_user_info where unionid = ? and source = ? limit 1";
            SQLReady sqlReady2 = new SQLReady(sql2,sessionInfo.getWeChatUserInfo().getUnionid(),sessionInfo.getWeChatUserInfo().getSource());
            List<WeChatUserInfo> weChatInfo = sqlManager.execute(sqlReady2,WeChatUserInfo.class);
            activityLog.setSponsorOpenid(weChatInfo.get(0).getOpenid());
            activityLog.setPlayerOpenid(StringUtils.isEmpty(sessionInfo.getWeChatUserInfo().getOpenid())?null:sessionInfo.getWeChatUserInfo().getOpenid());
            activityLog.setPlayerUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            activityLog.setCreateTime(new Date());
        }

        //新增
        activityLogDao.insert(activityLog);
        //redis解锁
        redisUtil.lockDel("kanjia" + queryParamsBargainAdd.getGoodsDefId(),identifier);
        return ResultUtil.success();
    }

    public Result groupGoodsInfo(QueryParamsGroup1 queryParamsGroup, HttpServletRequest request) {
        if(queryParamsGroup.getGoodsDefId() == null){
            ResultUtil.error(-1,"商品id缺失");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();
        String sql = "SELECT " +
                " DATE_FORMAT( a.activity_start_time, '%Y-%m-%d %H:%i:%s' ) activity_start_time, " +
                " DATE_FORMAT( a.activity_end_time, '%Y-%m-%d %H:%i:%s' ) activity_end_time, " +
                " a.goods_def_id, " +
                " d.goods_model_id, " +
                " b.goods_name, " +
                " b.goods_pic, " +
                " b.goods_description, " +
                " b.goods_tips, " +
                " d.goods_model_sale_price activity_price, " +
                "IF " +
                " ( a.activity_type_id = 1, '砍价', '拼团' ) type,  " +
                "( SELECT sponsor_unionid FROM activity_log WHERE activity_type_id = 2 AND goods_def_id = ? AND status = 1 AND player_unionid = ? LIMIT 1 ) sponsor_unionid " +
                "FROM " +
                " activity_goods a " +
                " LEFT JOIN goods_def b ON a.goods_def_id = b.goods_def_id " +
                " left join goods_model d on a.goods_def_id = d.goods_def_id  " +
                "WHERE " +
                " a.goods_def_id = ?";
        SQLReady sqlReady = new SQLReady(sql,queryParamsGroup.getGoodsDefId(),unionid,queryParamsGroup.getGoodsDefId());

        List<Map> query =sqlManager.execute(sqlReady,Map.class);

        return ResultUtil.success(query.size() > 0?query.get(0):null);
    }

    public Result selfGroupInfo(QueryParamsGroup queryParamsGroup, HttpServletRequest request) {
        if(queryParamsGroup.getGoodsDefId() == null){
            ResultUtil.error(-1,"商品id缺失");
        }
        String unionid = null;
        if(StringUtils.isEmpty(queryParamsGroup.getUnionid())){
            //查询的是自己的团
            SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
            unionid = sessionInfo.getWeChatUserInfo().getUnionid();
        }else{
            //查询的是别人的团
            unionid = queryParamsGroup.getUnionid();
        }

        String sql = "SELECT " +
                " a.sponsor_unionid, " +
                " b.nickname, " +
                " b.headimgurl, " +
                " c.activity_end_time  " +
                "FROM " +
                " activity_log a " +
                " LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) b ON a.player_unionid = b.unionid " +
                " LEFT JOIN activity_goods c ON a.goods_def_id = c.goods_def_id  " +
                " AND a.activity_type_id = c.activity_type_id  " +
                "WHERE " +
                " a.activity_type_id = 2  " +
                " AND a.goods_def_id = ?  " +
                " AND a.status = 1  " +
                " AND a.sponsor_unionid = ( SELECT sponsor_unionid FROM activity_log WHERE activity_type_id = 2 AND goods_def_id = ? AND status = 1 AND player_unionid = ?  limit 1)  " +
                "ORDER BY " +
                " a.create_time";
        SQLReady sqlReady = new SQLReady(sql,queryParamsGroup.getGoodsDefId(),queryParamsGroup.getGoodsDefId(),unionid);

        List<Map> query =sqlManager.execute(sqlReady,Map.class);

        return ResultUtil.success(query);
    }

    public Result recommendGroupInfo(QueryParamsGroupList queryParamsGroup) {
        if(queryParamsGroup.getGoodsDefId() == null){
            ResultUtil.error(-1,"商品id缺失");
        }

        String sql = "select * from (SELECT " +
                " a.sponsor_unionid, " +
                " b.nickname, " +
                " b.headimgurl, " +
                " c.activity_end_time  " +
                "FROM " +
                " activity_log a " +
                " LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) b ON a.player_unionid = b.unionid " +
                " LEFT JOIN activity_goods c ON a.goods_def_id = c.goods_def_id  " +
                " AND a.activity_type_id = c.activity_type_id  " +
                "WHERE " +
                " a.activity_type_id = 2  " +
                " AND a.goods_def_id = ?  " +
                " AND a.status = 1  " +
                " AND a.sponsor_unionid IN ( " +
                " SELECT " +
                "  a.sponsor_unionid  " +
                " FROM " +
                "  activity_log a " +
                "  LEFT JOIN activity_goods c ON a.goods_def_id = c.goods_def_id  " +
                " WHERE " +
                "  a.activity_type_id = 2  " +
                "  AND a.goods_def_id = ?  " +
                "  AND a.status = 1  " +
                "  AND now() > c.activity_start_time  " +
                "  AND c.activity_end_time > now()  " +
                " GROUP BY " +
                "  a.sponsor_unionid  " +
                " HAVING " +
                " count(*) < 4  " +
                " )  " +
                "ORDER BY " +
                " a.create_time) t " + (queryParamsGroup.getLimit() == null?" limit 2":"limit " + queryParamsGroup.getLimit());
        SQLReady sqlReady = new SQLReady(sql,queryParamsGroup.getGoodsDefId(),queryParamsGroup.getGoodsDefId());

        List<Map> query =sqlManager.execute(sqlReady,Map.class);
        Map<String, List<Map>> groupList = query.stream().collect(Collectors.groupingBy(map -> map.get("sponsorUnionid").toString()));
        List<List> lists = new ArrayList<>();
        for(List<Map> list1 : groupList.values()){
            lists.add(list1);
        }
        return ResultUtil.success(lists);
    }

    @Transactional
    public Result groupAdd(QueryParamsBargainAdd queryParamsBargainAdd, HttpServletRequest request) {
        if(queryParamsBargainAdd.getGoodsDefId() == null){
            return ResultUtil.error(-1,"商品id缺失");
        }
        if(queryParamsBargainAdd.getGoodsModelId() == null){
            return ResultUtil.error(-1,"商品规格id缺失");
        }
        //redis加锁,抢锁等待时间比较重要，过期时间不重要
        String identifier =  redisUtil.lockWithTimeout("pintuan" + queryParamsBargainAdd.getGoodsDefId(),6000,10000);

        //判断活动是否过期
        String sql11 = "select * from activity_goods where goods_def_id = ? and now() > activity_end_time";
        SQLReady sqlReady11 = new SQLReady(sql11,queryParamsBargainAdd.getGoodsDefId());
        List<ActivityGoods> activityGoods = sqlManager.execute(sqlReady11,ActivityGoods.class);
        if(activityGoods.size() > 0){
            return ResultUtil.error(-1,"商品活动已过期");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);

        //判断是否已经支付
        ViewOrderGoods viewOrderGoods = viewOrderGoodsDao.createLambdaQuery()
                .andEq("goods_def_id",queryParamsBargainAdd.getGoodsDefId())
                .andEq("goods_model_id",queryParamsBargainAdd.getGoodsModelId())
                .andEq("activity_type_id",2)
                .andEq("buyer_unionid",sessionInfo.getWeChatUserInfo().getUnionid())
                .andEq("buy_count", 1)
                .andEq("status",1).single();
        if(viewOrderGoods == null){
            throw new MyException(ResultEnums.NO_PAY_FOR_ACTIVITY);
        }


        String sql = "select * from goods_model where goods_model_id = ?";
        SQLReady sqlReady = new SQLReady(sql,queryParamsBargainAdd.getGoodsModelId());
        List<GoodsModel> goodsModels = sqlManager.execute(sqlReady,GoodsModel.class);
        if(goodsModels.size() != 1){
            return ResultUtil.error(-1,"商品规格数量为"+goodsModels.size()+"存在问题");
        }
        ActivityLog activityLog = new ActivityLog();
        //是否是自己开团，也就是第一个发起人
        if(sessionInfo.getWeChatUserInfo().getUnionid().equals(queryParamsBargainAdd.getSponsorUnionid())){
            //自己开团
            //判断是否以及有该商品的自己开团的记录
            String sql1 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid = ? and player_unionid = ?";
            SQLReady sqlReady1 = new SQLReady(sql1,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),sessionInfo.getWeChatUserInfo().getUnionid(),sessionInfo.getWeChatUserInfo().getUnionid());
            List<Map> hasSelfList = sqlManager.execute(sqlReady1,Map.class);
            if(hasSelfList.size() > 0){
                return ResultUtil.error(-1,"您已经发起过组团了");
            }
            //判断是否已经参与过该商品的组团，参与过不能再开团
            String sql2 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid != ? and player_unionid = ?";
            SQLReady sqlReady2 = new SQLReady(sql2,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),sessionInfo.getWeChatUserInfo().getUnionid(),sessionInfo.getWeChatUserInfo().getUnionid());
            List<Map> hasGroupList = sqlManager.execute(sqlReady2,Map.class);
            if(hasGroupList.size() > 0){
                return ResultUtil.error(-1,"您参与过该商品的组团了");
            }

            activityLog.setActivityTypeId(2);
            activityLog.setStatus(1);
            activityLog.setActivityPrice(goodsModels.get(0).getGoodsModelSalePrice());
            activityLog.setGoodsDefId(queryParamsBargainAdd.getGoodsDefId());
            activityLog.setGoodsModelId(queryParamsBargainAdd.getGoodsModelId());
            activityLog.setSponsorUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            activityLog.setSponsorOpenid(StringUtils.isEmpty(sessionInfo.getWeChatUserInfo().getOpenid())?null:sessionInfo.getWeChatUserInfo().getOpenid());
            activityLog.setPlayerOpenid(StringUtils.isEmpty(sessionInfo.getWeChatUserInfo().getOpenid())?null:sessionInfo.getWeChatUserInfo().getOpenid());
            activityLog.setPlayerUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            activityLog.setCreateTime(new Date());
        }else{
            //参与别人团
            //判断该团发起人是否已经开团，一定要开过团
            String sql5 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid = ? and player_unionid = ?";
            SQLReady sqlReady5 = new SQLReady(sql5,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),queryParamsBargainAdd.getSponsorUnionid(),queryParamsBargainAdd.getSponsorUnionid());
            List<Map> hasSelfList = sqlManager.execute(sqlReady5,Map.class);
            if(hasSelfList.size() == 0){
                return ResultUtil.error(-1,"您的朋友还未开团呢");
            }

            //判断一个人只能进一个商品的一个团
            String sql3 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and player_unionid = ?";
            SQLReady sqlReady3 = new SQLReady(sql3,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),sessionInfo.getWeChatUserInfo().getUnionid());
            List<Map> hasGroupList = sqlManager.execute(sqlReady3,Map.class);
            if(hasGroupList.size() > 0){
                return ResultUtil.error(-1,"您参与过该商品的组团了");
            }

            //商品组团只能4个人
            String sql4 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid = ?  ";
            SQLReady sqlReady4 = new SQLReady(sql4,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),queryParamsBargainAdd.getSponsorUnionid());
            List<ActivityLog> countList = sqlManager.execute(sqlReady4,ActivityLog.class);
            if(countList.size() == 4){
                return ResultUtil.error(-1,"该团已经满员啦");
            }

            activityLog.setActivityPrice(goodsModels.get(0).getGoodsModelSalePrice());
            activityLog.setActivityTypeId(2);
            activityLog.setStatus(1);
            activityLog.setGoodsDefId(queryParamsBargainAdd.getGoodsDefId());
            activityLog.setGoodsModelId(queryParamsBargainAdd.getGoodsModelId());
            activityLog.setSponsorUnionid(queryParamsBargainAdd.getSponsorUnionid());
            //由于是别人的团需要查询别人的openid
            String sql2 = "select * from we_chat_user_info where unionid = ? limit 1";
            SQLReady sqlReady2 = new SQLReady(sql2,sessionInfo.getWeChatUserInfo().getUnionid() );
            List<WeChatUserInfo> weChatInfo = sqlManager.execute(sqlReady2,WeChatUserInfo.class);
            activityLog.setSponsorOpenid(weChatInfo.get(0).getOpenid());
            activityLog.setPlayerOpenid(StringUtils.isEmpty(sessionInfo.getWeChatUserInfo().getOpenid())?null:sessionInfo.getWeChatUserInfo().getOpenid());
            activityLog.setPlayerUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            activityLog.setCreateTime(new Date());

            if(countList.size() == 3){
                //推送拼团成功
                countList.add(activityLog);
                for(int i=0;i<countList.size();i++){
                    //查询公众号openid,用于推送
                    SQLReady sqlReadyo = new SQLReady("select * from we_chat_user_info where unionid = ? and source = 1",countList.get(i).getPlayerUnionid());
                    List<WeChatUserInfo> weChatUserInfos = sqlManager.execute(sqlReadyo,WeChatUserInfo.class);
                    if(weChatUserInfos.size() > 0){
                        //推送
                        weChatPushMessageUtil.groupSuccess(goodsModels.get(0).getGoodsModelName(),goodsModels.get(0).getGoodsModelSalePrice().toString(),"***",weChatUserInfos.get(0).getOpenid());
                    }
                }
            }
        }

        //新增
        activityLogDao.insert(activityLog);
        //redis解锁
        redisUtil.lockDel("pintuan" + queryParamsBargainAdd.getGoodsDefId(),identifier);
        return ResultUtil.success();
    }

    @Transactional
    public Result groupAddForPaySuccess(QueryParamsBargainAdd queryParamsBargainAdd , OrderInfo orderInfo) {
        if(queryParamsBargainAdd.getGoodsDefId() == null){
            return ResultUtil.error(-1,"商品id缺失");
        }
        if(queryParamsBargainAdd.getGoodsModelId() == null){
            return ResultUtil.error(-1,"商品规格id缺失");
        }
        //redis加锁,抢锁等待时间比较重要，过期时间不重要
        String identifier =  redisUtil.lockWithTimeout("pintuan" + queryParamsBargainAdd.getGoodsDefId(),6000,10000);

        //判断活动是否过期
        String sql11 = "select * from activity_goods where goods_def_id = ? and now() > activity_end_time";
        SQLReady sqlReady11 = new SQLReady(sql11,queryParamsBargainAdd.getGoodsDefId());
        List<ActivityGoods> activityGoods = sqlManager.execute(sqlReady11,ActivityGoods.class);
        if(activityGoods.size() > 0){
            return ResultUtil.error(-1,"商品活动已过期");
        }
        //sessionInfoUtils.getSessionInfoByAuth(request);
        //### groupAdd 不同之处就是组装sessionInfo ###
        SessionInfo sessionInfo = new SessionInfo();
        WeChatUserInfo weChatUserInfo = weChatUserInfoDao.createLambdaQuery().andEq("openid",orderInfo.getBuyerOpenid())
                .andEq("unionid",orderInfo.getBuyerUnionid()).single();
        sessionInfo.setWeChatUserInfo(weChatUserInfo);
        //#########################################
        //判断是否已经支付
        ViewOrderGoods viewOrderGoods = viewOrderGoodsDao.createLambdaQuery()
                .andEq("goods_def_id",queryParamsBargainAdd.getGoodsDefId())
                .andEq("goods_model_id",queryParamsBargainAdd.getGoodsModelId())
                .andEq("activity_type_id",2)
                .andEq("buyer_unionid",sessionInfo.getWeChatUserInfo().getUnionid())
                .andEq("buy_count", 1)
                .andEq("status",1).single();
        if(viewOrderGoods == null){
            throw new MyException(ResultEnums.NO_PAY_FOR_ACTIVITY);
        }


        String sql = "select * from goods_model where goods_model_id = ?";
        SQLReady sqlReady = new SQLReady(sql,queryParamsBargainAdd.getGoodsModelId());
        List<GoodsModel> goodsModels = sqlManager.execute(sqlReady,GoodsModel.class);
        if(goodsModels.size() != 1){
            return ResultUtil.error(-1,"商品规格数量为"+goodsModels.size()+"存在问题");
        }
        ActivityLog activityLog = new ActivityLog();
        //是否是自己开团，也就是第一个发起人
        if(sessionInfo.getWeChatUserInfo().getUnionid().equals(queryParamsBargainAdd.getSponsorUnionid())){
            //自己开团
            //判断是否以及有该商品的自己开团的记录
            String sql1 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid = ? and player_unionid = ?";
            SQLReady sqlReady1 = new SQLReady(sql1,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),sessionInfo.getWeChatUserInfo().getUnionid(),sessionInfo.getWeChatUserInfo().getUnionid());
            List<Map> hasSelfList = sqlManager.execute(sqlReady1,Map.class);
            if(hasSelfList.size() > 0){
                return ResultUtil.error(-1,"您已经发起过组团了");
            }
            //判断是否已经参与过该商品的组团，参与过不能再开团
            String sql2 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid != ? and player_unionid = ?";
            SQLReady sqlReady2 = new SQLReady(sql2,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),sessionInfo.getWeChatUserInfo().getUnionid(),sessionInfo.getWeChatUserInfo().getUnionid());
            List<Map> hasGroupList = sqlManager.execute(sqlReady2,Map.class);
            if(hasGroupList.size() > 0){
                return ResultUtil.error(-1,"您参与过该商品的组团了");
            }

            activityLog.setActivityTypeId(2);
            activityLog.setStatus(1);
            activityLog.setActivityPrice(goodsModels.get(0).getGoodsModelSalePrice());
            activityLog.setGoodsDefId(queryParamsBargainAdd.getGoodsDefId());
            activityLog.setGoodsModelId(queryParamsBargainAdd.getGoodsModelId());
            activityLog.setSponsorUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            activityLog.setSponsorOpenid(StringUtils.isEmpty(sessionInfo.getWeChatUserInfo().getOpenid())?null:sessionInfo.getWeChatUserInfo().getOpenid());
            activityLog.setPlayerOpenid(StringUtils.isEmpty(sessionInfo.getWeChatUserInfo().getOpenid())?null:sessionInfo.getWeChatUserInfo().getOpenid());
            activityLog.setPlayerUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            activityLog.setCreateTime(new Date());
        }else{
            //参与别人团
            //判断该团发起人是否已经开团，一定要开过团
            String sql5 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid = ? and player_unionid = ?";
            SQLReady sqlReady5 = new SQLReady(sql5,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),queryParamsBargainAdd.getSponsorUnionid(),queryParamsBargainAdd.getSponsorUnionid());
            List<Map> hasSelfList = sqlManager.execute(sqlReady5,Map.class);
            if(hasSelfList.size() == 0){
                return ResultUtil.error(-1,"您的朋友还未开团呢");
            }

            //判断一个人只能进一个商品的一个团
            String sql3 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and player_unionid = ?";
            SQLReady sqlReady3 = new SQLReady(sql3,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),sessionInfo.getWeChatUserInfo().getUnionid());
            List<Map> hasGroupList = sqlManager.execute(sqlReady3,Map.class);
            if(hasGroupList.size() > 0){
                return ResultUtil.error(-1,"您参与过该商品的组团了");
            }

            //商品组团只能4个人
            String sql4 = "select * from activity_log where status = 1 and activity_type_id = 2 and goods_def_id = ? and goods_model_id = ? and sponsor_unionid = ?  ";
            SQLReady sqlReady4 = new SQLReady(sql4,queryParamsBargainAdd.getGoodsDefId(),queryParamsBargainAdd.getGoodsModelId(),queryParamsBargainAdd.getSponsorUnionid());
            List<ActivityLog> countList = sqlManager.execute(sqlReady4,ActivityLog.class);
            if(countList.size() == 4){
                return ResultUtil.error(-1,"该团已经满员啦");
            }

            activityLog.setActivityPrice(goodsModels.get(0).getGoodsModelSalePrice());
            activityLog.setActivityTypeId(2);
            activityLog.setStatus(1);
            activityLog.setGoodsDefId(queryParamsBargainAdd.getGoodsDefId());
            activityLog.setGoodsModelId(queryParamsBargainAdd.getGoodsModelId());
            activityLog.setSponsorUnionid(queryParamsBargainAdd.getSponsorUnionid());
            //由于是别人的团需要查询别人的openid
            String sql2 = "select * from we_chat_user_info where unionid = ? limit 1";
            SQLReady sqlReady2 = new SQLReady(sql2,sessionInfo.getWeChatUserInfo().getUnionid() );
            List<WeChatUserInfo> weChatInfo = sqlManager.execute(sqlReady2,WeChatUserInfo.class);
            activityLog.setSponsorOpenid(weChatInfo.get(0).getOpenid());
            activityLog.setPlayerOpenid(StringUtils.isEmpty(sessionInfo.getWeChatUserInfo().getOpenid())?null:sessionInfo.getWeChatUserInfo().getOpenid());
            activityLog.setPlayerUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
            activityLog.setCreateTime(new Date());

            if(countList.size() == 3){
                //推送拼团成功
                countList.add(activityLog);
                for(int i=0;i<countList.size();i++){
                    //查询公众号openid,用于推送
                    SQLReady sqlReadyo = new SQLReady("select * from we_chat_user_info where unionid = ? and source = 1",countList.get(i).getPlayerUnionid());
                    List<WeChatUserInfo> weChatUserInfos = sqlManager.execute(sqlReadyo,WeChatUserInfo.class);
                    if(weChatUserInfos.size() > 0){
                        //推送
                        weChatPushMessageUtil.groupSuccess(goodsModels.get(0).getGoodsModelName(),goodsModels.get(0).getGoodsModelSalePrice().toString(),"***",weChatUserInfos.get(0).getOpenid());
                    }
                }
            }
        }

        //新增
        activityLogDao.insert(activityLog);
        //redis解锁
        redisUtil.lockDel("pintuan" + queryParamsBargainAdd.getGoodsDefId(),identifier);
        return ResultUtil.success();
    }

    public Result selfSpaceStatistics(QueryParamsSelfSpaceStatistics queryParamsSelfSpaceStatistics, HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
//        SessionInfo sessionInfo = new SessionInfo();
//        WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
//        weChatUserInfo.setUnionid("o0tFauD-Mv_bta2Gs6mvQlvsCPlU");
//        sessionInfo.setWeChatUserInfo(weChatUserInfo);
        String sql = "SELECT " +
                " count(*) space_count, " +
                " IF(sum( a.read_count ) IS NULL,0,sum( a.read_count )) read_count, " +
                " IF(sum( a.like_count ) IS NULL,0,sum( a.like_count )) like_count, " +
                " ( SELECT count(*) FROM manli_space a LEFT JOIN manli_space_log b ON a.space_id = b.space_id WHERE a.unionid = ? ) space_log_count, " +
                " b.nickname, " +
                " b.headimgurl " +
                "FROM " +
                " manli_space a  left join (select *from we_chat_user_info group by unionid) b on a.unionid = b.unionid " +
                "WHERE " +
                " a.unionid = ?";
        String unionid = StringUtils.isEmpty(queryParamsSelfSpaceStatistics.getUnionid())?sessionInfo.getWeChatUserInfo().getUnionid():queryParamsSelfSpaceStatistics.getUnionid();
        SQLReady sqlReady = new SQLReady(sql,unionid,unionid);
        List<Map> maps = sqlManager.execute(sqlReady,Map.class);
        return ResultUtil.success(maps.size() > 0?maps.get(0):null);
    }

    public Result spaceList(QueryParamsSpaceList queryParamsSpaceList, HttpServletRequest request) throws Exception{
        ObjectEmptyUtil.spaceListIsEmpty(queryParamsSpaceList);
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();
//        SessionInfo sessionInfo = new SessionInfo();
//        WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
//        weChatUserInfo.setUnionid("o0tFauD-Mv_bta2Gs6mvQlvsCPlU");
//        sessionInfo.setWeChatUserInfo(weChatUserInfo);
//        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();
        if(queryParamsSpaceList.getType().intValue() == 0){
            //查询全部动态
            String sql = "SELECT " +
                    " a.*, " +
                    " DATE_FORMAT( a.create_time, '%m-%d %H:%i:%s' ) create_time_format, " +
                    " b.nickname, " +
                    " b.headimgurl, " +
                    " c.space_log_count, " +
                    " e.branch_id, " +
                    " e.partner_id," +
                    " f.like_count_id " +
                    "FROM " +
                    " manli_space a " +
                    " LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) b ON a.unionid = b.unionid " +
                    " LEFT JOIN ( SELECT space_id, count(*) space_log_count FROM manli_space_log GROUP BY space_id ) c ON a.space_id = c.space_id " +
                    " LEFT JOIN user_link_unionid d ON a.unionid = d.unionid " +
                    " LEFT JOIN user e ON d.user_id = e.user_id  " +
                    " LEFT JOIN ( select * from manli_space_like_count_log where type = 1 and unionid = ?) f ON a.space_id = f.subject_id  " +
                    " where 1=1 " +
                    (StringUtils.isEmpty(queryParamsSpaceList.getThemeTag())?" ":" and a.theme_tag like '%" + queryParamsSpaceList.getThemeTag() + "%'") +
                    " order by a.create_time desc,space_id";
            SQLReady sqlReady = new SQLReady(sql,unionid);
            PageQuery<Map> pageQuery = new PageQuery<Map>(queryParamsSpaceList.getPage().longValue(),queryParamsSpaceList.getLimit().longValue());
            PageQuery<Map> executePageQuery = sqlManager.execute(sqlReady, Map.class,pageQuery);
            for(int i=0;i<executePageQuery.getList().size();i++){
                if(executePageQuery.getList().get(i).get("createTime") != null){
                    Date date = (Date)executePageQuery.getList().get(i).get("createTime");
                    executePageQuery.getList().get(i).put("timeDistance",DateUtils.calculateTime(date));
                }
                //查询该条动态的前十条评论，要和评论分页接口保持一致，所以直接调用评论分页接口
                QueryParamsSpaceReviewList queryParamsSpaceReviewList = new QueryParamsSpaceReviewList();
                queryParamsSpaceReviewList.setPage(1L);
                queryParamsSpaceReviewList.setLimit(10L);
                queryParamsSpaceReviewList.setSpaceId(Integer.parseInt(executePageQuery.getList().get(i).get("spaceId").toString()));
                Result result = spaceReviewList(queryParamsSpaceReviewList, request);
                executePageQuery.getList().get(i).put("spaceLogs10",result.getData());
                executePageQuery.getList().get(i).put("spaceLogsRows",result.getRows());
            }
            return ResultUtil.success(executePageQuery.getList(),executePageQuery.getTotalRow());
        }else if(queryParamsSpaceList.getType().intValue() == 1){
            //查询自己的动态
            String sql = "SELECT " +
                    " a.*, " +
                    " DATE_FORMAT( a.create_time, '%m-%d %H:%i:%s' ) create_time_format, " +
                    " b.nickname, " +
                    " b.headimgurl, " +
                    " c.space_log_count, " +
                    " e.branch_id, " +
                    " e.partner_id," +
                    " f.like_count_id " +
                    "FROM " +
                    " manli_space a " +
                    " LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) b ON a.unionid = b.unionid " +
                    " LEFT JOIN ( SELECT space_id, count(*) space_log_count FROM manli_space_log GROUP BY space_id ) c ON a.space_id = c.space_id " +
                    " LEFT JOIN user_link_unionid d ON a.unionid = d.unionid " +
                    " LEFT JOIN user e ON d.user_id = e.user_id  " +
                    " LEFT JOIN ( select * from manli_space_like_count_log where type = 1 and unionid = ?) f ON a.space_id = f.subject_id  " +
                    " where 1=1 " +
                    (StringUtils.isEmpty(queryParamsSpaceList.getThemeTag())?" ":" and a.theme_tag like '%" + queryParamsSpaceList.getThemeTag() + "%'") +
                    " and a.unionid = ?" +
                    " order by a.create_time desc,space_id";
            SQLReady sqlReady = new SQLReady(sql,unionid,unionid);
            PageQuery<Map> pageQuery = new PageQuery<Map>(queryParamsSpaceList.getPage().longValue(),queryParamsSpaceList.getLimit().longValue());
            PageQuery<Map> executePageQuery = sqlManager.execute(sqlReady, Map.class,pageQuery);
            for(int i=0;i<executePageQuery.getList().size();i++){
                if(executePageQuery.getList().get(i).get("createTime") != null){
                    Date date = (Date)executePageQuery.getList().get(i).get("createTime");
                    executePageQuery.getList().get(i).put("timeDistance",DateUtils.calculateTime(date));
                }
                //查询该条动态的前十条评论，要和评论分页接口保持一致，所以直接调用评论分页接口
                QueryParamsSpaceReviewList queryParamsSpaceReviewList = new QueryParamsSpaceReviewList();
                queryParamsSpaceReviewList.setPage(1L);
                queryParamsSpaceReviewList.setLimit(10L);
                queryParamsSpaceReviewList.setSpaceId(Integer.parseInt(executePageQuery.getList().get(i).get("spaceId").toString()));
                Result result = spaceReviewList(queryParamsSpaceReviewList, request);
                executePageQuery.getList().get(i).put("spaceLogs10",result.getData());
                executePageQuery.getList().get(i).put("spaceLogsRows",result.getRows());
            }
            return ResultUtil.success(executePageQuery.getList(),executePageQuery.getTotalRow());
        }else if(queryParamsSpaceList.getType().intValue() == 2){
            //查询别人的动态
            if(StringUtils.isEmpty(queryParamsSpaceList.getUnionid())){
                return ResultUtil.error(-1,"查询对象的unionid为空");
            }
            String sql = "SELECT " +
                    " a.*, " +
                    " DATE_FORMAT( a.create_time, '%m-%d %H:%i:%s' ) create_time_format, " +
                    " b.nickname, " +
                    " b.headimgurl, " +
                    " c.space_log_count, " +
                    " e.branch_id, " +
                    " e.partner_id," +
                    " f.like_count_id " +
                    "FROM " +
                    " manli_space a " +
                    " LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) b ON a.unionid = b.unionid " +
                    " LEFT JOIN ( SELECT space_id, count(*) space_log_count FROM manli_space_log GROUP BY space_id ) c ON a.space_id = c.space_id " +
                    " LEFT JOIN user_link_unionid d ON a.unionid = d.unionid " +
                    " LEFT JOIN user e ON d.user_id = e.user_id  " +
                    " LEFT JOIN ( select * from manli_space_like_count_log where type = 1 and unionid = ?) f ON a.space_id = f.subject_id  " +
                    " where 1=1 " +
                    (StringUtils.isEmpty(queryParamsSpaceList.getThemeTag())?" ":" and a.theme_tag like '%" + queryParamsSpaceList.getThemeTag() + "%'") +
                    " and a.unionid = ?" +
                    " order by a.create_time desc,space_id";;
            SQLReady sqlReady = new SQLReady(sql,unionid,queryParamsSpaceList.getUnionid());
            PageQuery<Map> pageQuery = new PageQuery<Map>(queryParamsSpaceList.getPage().longValue(),queryParamsSpaceList.getLimit().longValue());
            PageQuery<Map> executePageQuery = sqlManager.execute(sqlReady, Map.class,pageQuery);
            for(int i=0;i<executePageQuery.getList().size();i++){
                if(executePageQuery.getList().get(i).get("createTime") != null){
                    Date date = (Date)executePageQuery.getList().get(i).get("createTime");
                    executePageQuery.getList().get(i).put("timeDistance",DateUtils.calculateTime(date));
                }
                //查询该条动态的前十条评论，要和评论分页接口保持一致，所以直接调用评论分页接口
                QueryParamsSpaceReviewList queryParamsSpaceReviewList = new QueryParamsSpaceReviewList();
                queryParamsSpaceReviewList.setPage(1L);
                queryParamsSpaceReviewList.setLimit(10L);
                queryParamsSpaceReviewList.setSpaceId(Integer.parseInt(executePageQuery.getList().get(i).get("spaceId").toString()));
                Result result = spaceReviewList(queryParamsSpaceReviewList, request);
                executePageQuery.getList().get(i).put("spaceLogs10",result.getData());
                executePageQuery.getList().get(i).put("spaceLogsRows",result.getRows());
            }
            return ResultUtil.success(executePageQuery.getList(),executePageQuery.getTotalRow());
        }

        return ResultUtil.success();
    }

    public Result spaceReviewList(QueryParamsSpaceReviewList queryParamsSpaceReviewList, HttpServletRequest request)throws Exception {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();
//        SessionInfo sessionInfo = new SessionInfo();
//        WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
//        weChatUserInfo.setUnionid("o0tFauD-Mv_bta2Gs6mvQlvsCPlU");
//        sessionInfo.setWeChatUserInfo(weChatUserInfo);
//        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();
        //查询使用union all上面的话是一小时之内的数据，下面是一大于一小时之后的数据，按点赞排序
        String sql = "SELECT " +
                " *  " +
                "FROM " +
                " ( " +
                "  ( " +
                "  SELECT " +
                "   a.*, " +
                "   DATE_FORMAT( a.create_time, '%m-%d %H:%i:%s' ) create_time_format, " +
                "   b.nickname reviewer_nickname, " +
                "   c.nickname respondent_nickname, " +
                "   b.headimgurl reviewer_headimgurl, " +
                "   c.headimgurl respondent_headimgurl, " +
                "   1 sort_line, " +
                "   a.create_time AS sort_create_time, " +
                "   a.like_count sort_like_count , " +
                "   d.like_count_id " +
                "  FROM " +
                "   manli_space_log a " +
                "   LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) b ON a.reviewer_unionid = b.unionid " +
                "   LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) c ON a.respondent_unionid = c.unionid  " +
                "   LEFT JOIN ( select * from manli_space_like_count_log where type = 2 and unionid = ?) d ON a.manli_space_log_id = d.subject_id  " +
                "  WHERE " +
                "   a.create_time > NOW()- INTERVAL 2 HOUR  " +
                "   AND a.space_id = ?  " +
                "  ORDER BY " +
                "   a.create_time DESC  " +
                "  ) UNION ALL " +
                "  ( " +
                "  SELECT " +
                "   a.*, " +
                "   DATE_FORMAT( a.create_time, '%m-%d %H:%i:%s' ) create_time_format, " +
                "   b.nickname reviewer_nickname, " +
                "   c.nickname respondent_nickname, " +
                "   b.headimgurl reviewer_headimgurl, " +
                "   c.headimgurl respondent_headimgurl, " +
                "   2 sort_line, " +
                "   a.create_time AS sort_create_time, " +
                "   a.like_count sort_like_count, " +
                "   d.like_count_id " +
                "  FROM " +
                "   manli_space_log a " +
                "   LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) b ON a.reviewer_unionid = b.unionid " +
                "   LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) c ON a.respondent_unionid = c.unionid  " +
                "   LEFT JOIN ( select * from manli_space_like_count_log where type = 2 and unionid = ?) d ON a.manli_space_log_id = d.subject_id  " +
                "  WHERE " +
                "   a.create_time < NOW()- INTERVAL 2 HOUR  " +
                "   AND a.space_id = ?  " +
                "  ORDER BY " +
                "   a.like_count DESC  " +
                "  )  " +
                " ) t3  " +
                "ORDER BY " +
                " t3.sort_line ASC, " +
                " t3.sort_like_count DESC";
        SQLReady sqlReady = new SQLReady(sql,unionid,queryParamsSpaceReviewList.getSpaceId(),unionid,queryParamsSpaceReviewList.getSpaceId());
        PageQuery<Map> pageQuery = new PageQuery<Map>(queryParamsSpaceReviewList.getPage().longValue(),queryParamsSpaceReviewList.getLimit().longValue());
        PageQuery<Map> executePageQuery = sqlManager.execute(sqlReady, Map.class,pageQuery);
        for(int i=0;i<executePageQuery.getList().size();i++){
            if(executePageQuery.getList().get(i).get("createTime") != null){
                Date date = (Date)executePageQuery.getList().get(i).get("createTime");
                executePageQuery.getList().get(i).put("timeDistance",DateUtils.calculateTime(date));
            }
        }
        return  ResultUtil.success(executePageQuery.getList(),executePageQuery.getTotalRow());
    }

    @Transactional
    public Result spaceAdd(ManliSpace manliSpace, HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        ObjectEmptyUtil.manliSpaceIsEmpty(manliSpace);
        manliSpace.setUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
        manliSpace.setOpenid(sessionInfo.getWeChatUserInfo().getOpenid());
        manliSpace.setCreateTime(new Date());
        manliSpaceDao.insert(manliSpace);
        return ResultUtil.success();
    }

    @Transactional
    public Result spaceReviewAdd(ManliSpaceLog manliSpaceLog, HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        ObjectEmptyUtil.manliSpaceLogIsEmpty(manliSpaceLog);
        manliSpaceLog.setReviewerUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
        manliSpaceLog.setReviewerOpenid(sessionInfo.getWeChatUserInfo().getOpenid());
        if(StringUtils.isEmpty(manliSpaceLog.getRespondentUnionid())){
            SQLReady sqlReady = new SQLReady("select * from we_chat_user_info where unionid = ? and source = 2",manliSpaceLog.getRespondentUnionid());
            List<WeChatUserInfo> weChatUserInfos = sqlManager.execute(sqlReady,WeChatUserInfo.class);
            if(weChatUserInfos.size() > 0){
                manliSpaceLog.setRespondentOpenid(weChatUserInfos.get(0).getOpenid());
            }
        }
        manliSpaceLog.setCreateTime(new Date());
        manliSpaceLogDao.insert(manliSpaceLog);
        return ResultUtil.success();
    }

    @Transactional
    public Result spaceLikeCountAdd(QueryParamsSelfCountAdd queryParamsSelfCountAdd, HttpServletRequest request) {
        if(queryParamsSelfCountAdd.getSpaceId() == null){
            return ResultUtil.error(-1,"动态id为空");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        //查询判断是否已经给该条动态点过赞了
        String sql = "select * from manli_space_like_count_log where type = 1 and unionid = ? and subject_id = ?";
        SQLReady sqlReady = new SQLReady(sql,sessionInfo.getWeChatUserInfo().getUnionid(),queryParamsSelfCountAdd.getSpaceId());
        List<ManliSpaceLikeCountLog> manliSpaceLikeCountLogs = sqlManager.execute(sqlReady,ManliSpaceLikeCountLog.class);
        if(manliSpaceLikeCountLogs.size() > 0){
            return ResultUtil.error(-1,"您已经点过赞了");
        }
        //查询该条动态，如果点赞量为0，则变为1，如果已经有值，+1更新
        ManliSpace manliSpace = manliSpaceDao.single(queryParamsSelfCountAdd.getSpaceId());
        if(manliSpace != null){
            ManliSpace manliSpace1 = new ManliSpace();
            manliSpace1.setSpaceId(manliSpace.getSpaceId());
            if(manliSpace.getLikeCount() == null){
                manliSpace1.setLikeCount(1);
            }else{
                manliSpace1.setLikeCount(manliSpace.getLikeCount() + 1);
            }
            manliSpaceDao.updateTemplateById(manliSpace1);
        }
        //往点赞记录添加记录
        ManliSpaceLikeCountLog manliSpaceLikeCountLog = new ManliSpaceLikeCountLog();
        manliSpaceLikeCountLog.setType(1);
        manliSpaceLikeCountLog.setUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
        manliSpaceLikeCountLog.setOpenid(sessionInfo.getWeChatUserInfo().getOpenid());
        manliSpaceLikeCountLog.setSubjectId(queryParamsSelfCountAdd.getSpaceId());
        manliSpaceLikeCountLog.setCreateTime(new Date());
        manliSpaceLikeCountLogDao.insert(manliSpaceLikeCountLog);
        return ResultUtil.success();
    }

    @Transactional
    public Result spaceReadCountAdd(QueryParamsSelfCountRead queryParamsSelfCountAdd) {
        if(queryParamsSelfCountAdd.getSpaceId() == null){
            return ResultUtil.error(-1,"动态id为空");
        }
        queryParamsSelfCountAdd.getSpaceId().forEach(spaceId -> {
            //查询该条动态，如果点赞量为0，则变为1，如果已经有值，+1更新
            ManliSpace manliSpace = manliSpaceDao.single(spaceId);
            if(manliSpace != null){
                ManliSpace manliSpace1 = new ManliSpace();
                manliSpace1.setSpaceId(manliSpace.getSpaceId());
                if(manliSpace.getReadCount() == null){
                    manliSpace1.setReadCount(1);
                }else{
                    manliSpace1.setReadCount(manliSpace.getReadCount() + 1);
                }
                manliSpaceDao.updateTemplateById(manliSpace1);
            }
        });

        return ResultUtil.success();
    }

    @Transactional
    public Result spaceReviewLikeCountAdd(QueryParamsSelfReviewCountAdd queryParamsSelfReviewCountAdd, HttpServletRequest request) {
        if(queryParamsSelfReviewCountAdd.getManliSpaceLogId() == null){
            return ResultUtil.error(-1,"评论id为空");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        //查询判断是否已经给该条评论点过赞了
        String sql = "select * from manli_space_like_count_log where type = 2 and unionid = ? and subject_id = ?";
        SQLReady sqlReady = new SQLReady(sql,sessionInfo.getWeChatUserInfo().getUnionid(),queryParamsSelfReviewCountAdd.getManliSpaceLogId());
        List<ManliSpaceLikeCountLog> manliSpaceLikeCountLogs = sqlManager.execute(sqlReady,ManliSpaceLikeCountLog.class);
        if(manliSpaceLikeCountLogs.size() > 0){
            return ResultUtil.error(-1,"您已经点过赞了");
        }
        //查询该条评论，如果点赞量为0，则变为1，如果已经有值，+1更新
        ManliSpaceLog manliSpace = manliSpaceLogDao.single(queryParamsSelfReviewCountAdd.getManliSpaceLogId());
        if(manliSpace != null){
            ManliSpaceLog manliSpace1 = new ManliSpaceLog();
            manliSpace1.setManliSpaceLogId(queryParamsSelfReviewCountAdd.getManliSpaceLogId());
            if(manliSpace.getLikeCount() == null){
                manliSpace1.setLikeCount(1);
            }else{
                manliSpace1.setLikeCount(manliSpace.getLikeCount() + 1);
            }
            manliSpaceLogDao.updateTemplateById(manliSpace1);
        }
        //往点赞记录添加记录
        ManliSpaceLikeCountLog manliSpaceLikeCountLog = new ManliSpaceLikeCountLog();
        manliSpaceLikeCountLog.setType(2);
        manliSpaceLikeCountLog.setUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
        manliSpaceLikeCountLog.setOpenid(sessionInfo.getWeChatUserInfo().getOpenid());
        manliSpaceLikeCountLog.setSubjectId(queryParamsSelfReviewCountAdd.getManliSpaceLogId());
        manliSpaceLikeCountLog.setCreateTime(new Date());
        manliSpaceLikeCountLogDao.insert(manliSpaceLikeCountLog);
        return ResultUtil.success();
    }

    /**
     * 查询活动商品支付金额,无符合条件则返回null
     * @param params
     * @return
     */
    public Double checkActivityPayPrice(QueryParamsCheckPayPrice params) {
        ObjectEmptyUtil.checkPayPriceIsEmpty(params);
        Double payPrice = null;
        //查询商品规格价格
        String sql2 = "select * from goods_model where goods_model_id = ?";
        SQLReady sqlReady2 = new SQLReady(sql2,params.getGoodsModelId());
        List<GoodsModel> goodsModels = sqlManager.execute(sqlReady2,GoodsModel.class);
        if(goodsModels.size() == 0){
            return null;
        }
        GoodsModel goodsModel = goodsModels.get(0);

        if(params.getActivityType().intValue() == 1){
            //砍价
            //需判断砍价活动是否已经砍到低价，或者活动结束

            //先查询根据unionid查询发起人unionid
            String sql1 = "select * from activity_log where status = 1 and activity_type_id = 1 and goods_def_id = ? and goods_model_id = ? and player_unionid = ?";
            SQLReady sqlReady1 = new SQLReady(sql1,params.getGoodsDefId(),params.getGoodsModelId(),params.getUnionid());
            List<ActivityLog> activityLogs = sqlManager.execute(sqlReady1,ActivityLog.class);
            if(activityLogs.size() == 0){
                //没有砍价记录说明是原价
                return goodsModel.getGoodsModelSourcePrice();
            }
            String sponsorUnionid = activityLogs.get(0).getSponsorUnionid();

            //判断砍价活动是否已经砍到低价
            String sql3 = "select sum(activity_price) sum_price from activity_log where status = 1 and goods_def_id = ? and goods_model_id = ? and activity_type_id = 1 and sponsor_unionid = ?";
            SQLReady sqlReady3 = new SQLReady(sql3,params.getGoodsDefId(),params.getGoodsModelId(),sponsorUnionid);
            List<Map> sumPrice = sqlManager.execute(sqlReady3,Map.class);
            if(sumPrice.size() > 0){
                if(sumPrice.get(0).get("sumPrice") != null){
                    //现价差 = 销售价 - （原价 - 已经砍了的总和）
                    double cha = goodsModel.getGoodsModelSalePrice() - (goodsModel.getGoodsModelSourcePrice() - Double.parseDouble(sumPrice.get(0).get("sumPrice").toString()));
                    if(cha == 0){
                        //已经等于销售价了
                        return goodsModel.getGoodsModelSalePrice();
                    }else{
                        //还没等于销售价，此时判断是否活动结束，如果结束则还能发起原价-已经砍了的金额支付
                        String sql4 = "select * from activity_goods where goods_def_id = ? and status = 1 and activity_type_id = 1 and now() > activity_end_time";
                        SQLReady sqlReady4 = new SQLReady(sql4,params.getGoodsDefId());
                        List<ActivityGoods> activityGoodsList = sqlManager.execute(sqlReady4,ActivityGoods.class);
                        if(activityGoodsList.size() > 0){
                            //活动结束
                            return goodsModel.getGoodsModelSourcePrice() - Double.parseDouble(sumPrice.get(0).get("sumPrice").toString());
                        }else{
                            return null;
                        }
                    }
                }
            }
        }else if(params.getActivityType().intValue() == 2){
            //直接返回销售价
           return goodsModel.getGoodsModelSalePrice();
        }else if(params.getActivityType().intValue() == 3){
            //一元拍卖
            //一元拍卖结束才能支付
            String sql4 = "select * from activity_goods where goods_def_id = ? and status = 1 and activity_type_id = 3 and now() > activity_end_time";
            SQLReady sqlReady4 = new SQLReady(sql4,params.getGoodsDefId());
            List<ActivityGoods> activityGoodsList = sqlManager.execute(sqlReady4,ActivityGoods.class);
            if(activityGoodsList.size() > 0){
                //活动结束
                String sql = "select * from activity_log where activity_type_id = 3 and goods_def_id = ? and goods_model_id = ? and status = 1 order by activity_price desc limit 1";
                SQLReady sqlReady = new SQLReady(sql,params.getGoodsDefId(),params.getGoodsModelId());
                List<ActivityLog> activityLogs = sqlManager.execute(sqlReady,ActivityLog.class);
                if(activityLogs.size() > 0){
                    //出价最高者才能支付
                    if(activityLogs.get(0).getPlayerUnionid().equals(params.getUnionid())){
                        return activityLogs.get(0).getActivityPrice();
                    }else{
                        return null;
                    }
                }else{
                    return null;
                }
            }else{
                return null;
            }
        }
        return payPrice;
    }

    /**
     * 个人中心我的订单列表信息
     * @param myOrderInfo
     * @param request
     * @return
     */
    public Result getMineOrderInfo(QueryParamsMyOrderInfo myOrderInfo, HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);

        String paramStr = "";
        if(myOrderInfo.getStatus() != null){
            paramStr += " and status = " + myOrderInfo.getStatus() +" ";
        }
        //获取指定数量的主订单号
        List<ViewOrderGoods> limitLists =  sqlManager.execute(new SQLReady(
                "select * from view_order_goods " +
                        "where 1=1 " +
                        "and buyer_unionid = ? " +
                        paramStr +
                        "group by order_no_main   " + //, status
                        "order by create_time desc " +
                        "limit ? , ? ",
                sessionInfo.getWeChatUserInfo().getUnionid() ,
                (myOrderInfo.getPage()-1)*myOrderInfo.getLimit() ,
                myOrderInfo.getLimit()),ViewOrderGoods.class);
        String sqlOrderNoMainStr = "" ;
        for(ViewOrderGoods viewOrderGood : limitLists){
            sqlOrderNoMainStr+=viewOrderGood.getOrderNoMain()+",";
        }
        if(sqlOrderNoMainStr.length() == 0 ){
            return ResultUtil.success(null);
        }
        sqlOrderNoMainStr = sqlOrderNoMainStr.substring(0,sqlOrderNoMainStr.length()-1);
        //获取数量
        List<ViewOrderGoods> countList = sqlManager.execute(
                new SQLReady("select * from view_order_goods " +
                        "where 1=1 " +
                        "and buyer_unionid = ? " +
                        paramStr +
                        "group by order_no_main  " , sessionInfo.getWeChatUserInfo().getUnionid()),ViewOrderGoods.class);
        //获取列表
        List<ViewOrderGoods> viewOrderGoodsList = sqlManager.execute(new SQLReady(
                "select * from view_order_goods " +
                        "where 1=1 " +
                        "and buyer_unionid = ? " +
                        paramStr +
                        "and find_in_set(order_no_main, ? ) > 0 " +
                        "order by create_time desc " ,
                sessionInfo.getWeChatUserInfo().getUnionid() ,
                sqlOrderNoMainStr) ,ViewOrderGoods.class);

        Map<String,List<ViewOrderGoods>> ret =
                viewOrderGoodsList
                        .stream()
                        .collect(Collectors.groupingBy(e -> fetchGroupKeyForGetMineOrderInfo(e),LinkedHashMap::new,Collectors.toList()));
        //倒序
        List<List<ViewOrderGoods>> retList = new ArrayList<>();
        for (Map.Entry<String, List<ViewOrderGoods>> entry : ret.entrySet()) {
            retList.add(entry.getValue());
        }
        return ResultUtil.success(retList,Long.valueOf(countList.size()));
    }
    //我的订单分组
    private String fetchGroupKeyForGetMineOrderInfo(ViewOrderGoods viewOrderGoods){
        return viewOrderGoods.getOrderNoMain() ;
    }

    public Result goodsAppraiseAdd(AppraiseLog appraiseLog, HttpServletRequest request) {
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        ObjectEmptyUtil.appraiseLogIsEmpty(appraiseLog);

        //查询该用户是否已经评价过改订单该商品
        String sql = "SELECT " +
                " *  " +
                "FROM " +
                " appraise_log  " +
                "WHERE " +
                " unionid = ?  " +
                " AND branch_id = ?  " +
                (appraiseLog.getPartnerId() == null?" ":"" + " AND partner_id = " + appraiseLog.getPartnerId()) +
                " AND goods_def_id = ?  " +
                " AND goods_model_id = ?  " +
                " AND order_no_main = ?  " +
                " AND order_no_sub = ?";
        List<AppraiseLog> appraiseLogs = appraiseLogDao.execute(sql,sessionInfo.getWeChatUserInfo().getUnionid(),
                appraiseLog.getBranchId(),appraiseLog.getGoodsDefId(),appraiseLog.getGoodsModelId(),appraiseLog.getOrderNoMain(),appraiseLog.getOrderNoSub());
        if(appraiseLogs.size() > 0){
            return ResultUtil.error(-1,"您已经评价过该商品了");
        }

        //新增
        appraiseLog.setOpenid(sessionInfo.getWeChatUserInfo().getOpenid());
        appraiseLog.setUnionid(sessionInfo.getWeChatUserInfo().getUnionid());
        appraiseLog.setCreateTime(new Date());
        appraiseLogDao.insert(appraiseLog);
        return ResultUtil.success();
    }

    public Result selfSpaceThemes(QueryParamsSelfSpaceThemes themes, HttpServletRequest request) {
        //首先查询所有动态的主题字段，这里数据量大的时候会影响性能。到时候再加筛选条件好了，比如半年时间内的
        String sql4 = "select theme_tag from manli_space";
        SQLReady sqlReady4 = new SQLReady(sql4);
        List<String> themeTags = sqlManager.execute(sqlReady4,String.class);

        //然后对主题进行去重和标签数量统计
        //1.将所有主题标签放在同一个list
        List<String> tagList = new ArrayList<>();
        themeTags.stream().forEach(s -> {
            if(!StringUtils.isEmpty(s)){
                List<String> array = JSON.parseArray(s).toJavaList(String.class);
                tagList.addAll(array);
            }
        });
        //2.统计list中对象的重复次数
        Map<String, Long> map = tagList.stream().collect(Collectors.groupingBy(p -> p,Collectors.counting()));
        //3.map转换list
        List<ThemeCount> returnList = new ArrayList<>();
        map.forEach((k, v) -> {
            ThemeCount themeCount = new ThemeCount();
            themeCount.setTheme(k);
            themeCount.setThemeCount(v);
            returnList.add(themeCount);
        });
        //4.根据数量排序;
        returnList.sort(Comparator.comparing(ThemeCount::getThemeCount).reversed());

        return ResultUtil.success(themes.getLimit() == null?returnList:returnList.subList(0,(returnList.size() > themes.getLimit()?themes.getLimit():returnList.size())));
    }

    public Result querySpaceById(QueryParamsSpace queryParamsSpace, HttpServletRequest request) throws Exception{
        if(queryParamsSpace.getSpaceId() == null){
            return ResultUtil.error(-1,"缺少动态id");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();
//        SessionInfo sessionInfo = new SessionInfo();
//        WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
//        weChatUserInfo.setUnionid("o0tFauD-Mv_bta2Gs6mvQlvsCPlU");
//        sessionInfo.setWeChatUserInfo(weChatUserInfo);
//        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();
        String sql = "SELECT " +
                " a.*, " +
                " DATE_FORMAT( a.create_time, '%m-%d %H:%i:%s' ) create_time_format, " +
                " b.nickname, " +
                " b.headimgurl, " +
                " c.space_log_count, " +
                " e.branch_id, " +
                " e.partner_id, " +
                " f.like_count_id " +
                "FROM " +
                " manli_space a " +
                " LEFT JOIN ( SELECT * FROM we_chat_user_info GROUP BY unionid ) b ON a.unionid = b.unionid " +
                " LEFT JOIN ( SELECT space_id, count(*) space_log_count FROM manli_space_log GROUP BY space_id ) c ON a.space_id = c.space_id " +
                " LEFT JOIN user_link_unionid d ON a.unionid = d.unionid " +
                " LEFT JOIN user e ON d.user_id = e.user_id  " +
                " LEFT JOIN ( select * from manli_space_like_count_log where type = 1 and unionid = ?) f ON a.space_id = f.subject_id  " +
                " where 1=1 and a.space_id = ?";
        SQLReady sqlReady = new SQLReady(sql,unionid,queryParamsSpace.getSpaceId());
        List<Map> list = sqlManager.execute(sqlReady, Map.class);
        if(list.size() > 0){
            if(list.get(0).get("createTime") != null){
                Date date = (Date)list.get(0).get("createTime");
                list.get(0).put("timeDistance",DateUtils.calculateTime(date));
            }
            //查询该条动态的前十条评论，要和评论分页接口保持一致，所以直接调用评论分页接口
            QueryParamsSpaceReviewList queryParamsSpaceReviewList = new QueryParamsSpaceReviewList();
            queryParamsSpaceReviewList.setPage(1L);
            queryParamsSpaceReviewList.setLimit(10L);
            queryParamsSpaceReviewList.setSpaceId(queryParamsSpace.getSpaceId().intValue());
            Result result = spaceReviewList(queryParamsSpaceReviewList, request);
            list.get(0).put("spaceLogs10",result.getData());
            list.get(0).put("spaceLogsRows",result.getRows());
        }

        return ResultUtil.success(list.get(0));
    }

    public Result querySpaceLogById(QueryParamsSpaceLog queryParamsSpace, HttpServletRequest request) {
        if(queryParamsSpace.getManliSpaceLogId() == null){
            return ResultUtil.error(-1,"缺少动态id");
        }
        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();
//        SessionInfo sessionInfo = new SessionInfo();
//        WeChatUserInfo weChatUserInfo = new WeChatUserInfo();
//        weChatUserInfo.setUnionid("o0tFauD-Mv_bta2Gs6mvQlvsCPlU");
//        sessionInfo.setWeChatUserInfo(weChatUserInfo);
//        String unionid = sessionInfo.getWeChatUserInfo().getUnionid();
        //查询使用union all上面的话是一小时之内的数据，下面是一大于一小时之后的数据，按点赞排序
        String sql = "SELECT " +
                " a.*,d.like_count_id " +
                "FROM " +
                " manli_space_log a " +
                " LEFT JOIN (SELECT * FROM manli_space_like_count_log WHERE type = 2 AND unionid = ?) d ON a.manli_space_log_id = d.subject_id  " +
                "WHERE " +
                " manli_space_log_id = ?";
        SQLReady sqlReady = new SQLReady(sql,unionid,queryParamsSpace.getManliSpaceLogId());
        List<Map> list = sqlManager.execute(sqlReady, Map.class);

        return ResultUtil.success(list.size() > 0?list.get(0):null);
    }

    public Result getWechatFuncControllerList(QueryWechatFuncControllerPojo pojo , HttpServletRequest request) {
        String sql = "SELECT " +
                "  label_id as id " +
                "FROM " +
                "  `wechat_func_controller` " +
                "where can_show = 1 " +
                "and type = "+ pojo.getType();
        SQLReady sqlReady = new SQLReady(sql);
        List<Map> list = sqlManager.execute(sqlReady, Map.class);
        return ResultUtil.success(list);
    }
}
